首页 > 解决方案 > 试图与 flex 水平对齐

问题描述

我尝试创建 2 个菜单栏,但我无法水平对齐菜单按钮,因为元素的数量不一样。我尝试使用 max-witdh、flex-basis、flex-grow、flex-shrink 属性,但无法实现我想要的。

在这里你可以找到一个代码片段:

body {
  background-color: black;
  text-align: center;
  color: white;
  font-family: Arial, Helvetica, sans-serif;
}
.row{
    display: flex;
    flex-direction: row;
    flex: 1;
    width: 100%;
   
}
  p, .myCustomButton {
    border-radius: 4px;
    height: 2.8em;
    font-size: 1.6rem;
    color: #fff;
    background-color: red;
    margin: 0.4rem 0.2rem;
    padding: 0 1em;
    flex: 1;
  }
  .row2 {
    justify-content: flex-end;
  }
  .myCustomButton {
    max-width: 20%;
    flex: 0.1 0.1 auto;
  }
<div class='row'>
  <p>test</p>
  <p>test</p>
  <p>test</p>
  <p>test</p>
  <p>test</p>
</div>

<div class='row row2'>
  <p class='myCustomButton'>test</p>
</div>

我希望在每种情况下(响应式)我的自定义按钮和测试按钮之间的大小相同。我可以通过哪种方式实现这一目标?我应该寻找哪个 CSS 属性?对我来说它是 flex-basis 但我不知道如何使用它,我已经从 mozzila doc 中阅读了它的工作原理,也许我错过了一些东西

提前致谢。

标签: htmlcssflexboxresponsive

解决方案


最后一个元素不适合其他元素大小的原因是因为边距。<div>在周围添加一个额外的<p>并告诉一个row2不要超过 20% 的基础对我来说是诀窍:

<div class='row row2'>
   <div>
    <p class='myCustomButton'>test</p>
   </div>
</div>

.row2 > div {
  flex: 0 1 20%;
}

.row {
  display: flex;
  width: 100%;
}

.row > div {
  flex: 1 1 20%;
}

p {
  border-radius: 4px;
  height: 2.8em;
  font-size: 1.6rem;
  color: #fff;
  background-color: red;
  margin: 0.4rem 0.2rem;
  padding: 0 1em;
  flex: 1;
}

.row2 {
  justify-content: flex-end;
}

.row2 > div {
  flex: 0 1 20%;
}
<div class='row'>
    <div>
      <p>test</p>
    </div>
    <div>
      <p>test</p>
    </div>
    <div>
      <p>test</p>
    </div>
     <div>
      <p>test</p>
    </div>
    <div>
      <p>test</p>
    </div>
</div>

<div class='row row2'>
    <div><p class='myCustomButton'>test</p></div>
</div>

如果可能的话,我会推荐使用 CSS 网格,这样更容易:

https://codepen.io/sergiofruto/pen/zYqmKYW


推荐阅读