如何将元素与另一个与flex对齐的元素对齐?

时间:2017-02-27 19:49:05

标签: html css flexbox

我在flex容器中有两行元素,它们使用CSS属性-webkit-flex-flow: row wrap;justify-content: space-around;居中。在这一行的上方,我想要一个带有文本的div,它与行中最左边的div垂直对齐。

是否可以仅使用CSS来执行此操作,并要求元素保留其display: flex;属性?

这是我的HTML:

<div class="flex-container">
  <div class="info-box">

  </div>
  <div class="type-one">

  </div>
  <div class="type-one">

  </div>
</div>

这是css:

.flex-container {
    padding: 0;
    margin: 0;

    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;

    -webkit-flex-flow: row wrap;
    justify-content: space-around;
}

.type-one{
  width: 45%;
  height: 50px;
  background: tomato;

  text-align: left;

  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;

  -webkit-flex-flow: row wrap;
  justify-content: flex-start;
}
.info-box{
  width: 100%;
  height: 10px;
  background: tomato;
  margin-bottom: 3px;
}

Here是一个小提琴的例子。你可以看到顶行是如何从左边开始的(因为它有flex-start对齐),但我希望它从第二行中最左边元素开始的位置开始。这是否可以满足给定的要求?

编辑:我意识到我可以在信息框中添加2.5%的边距或使其宽度为95%,但我更喜欢一种相对于第一类元素的解决方案,这样如果我改变它们的宽度信息框将自动重新对齐它们。

1 个答案:

答案 0 :(得分:1)

要让它们在左边缘对齐,请将父元素的左/右边距设置为匹配中间的列开始的位置。将justify-contentspace-around更改为space-between,以便中间列的左侧间距不会更改,并使用这些元素的宽度在它们之间创建空间。

.flex-container {
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    
    padding: 0;
    margin: 0;
    width: 95%;
    margin: auto;
}

.type-one{
  height: 50px;
  background: tomato;
  text-align: left;
  width: 47.5%;
}

.type-two{
  width: 100%;
  margin-top: 10px;
  font-size: 15px;
  text-align: center;
  height: 20px;
  background: tomato;
}

.info-box{
  width: 100%;
  height: 10px;
  background: tomato;
  margin-bottom: 3px;
}
<div class="flex-container">
  <div class="info-box"></div>
  <div class="type-one"></div><div class="type-one"></div>
  <div class="type-two"></div>
</div>