如何在 flex 容器中将两个居中的 div 顶部对齐?

3

这是我的代码示例:

.flex-container {
  height: 300px;
  width: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ffeeee
}

#item1 {
  width: 100px;
  height: 100px;
  background-color: blue;
}

#item2 {
  width: 120px;
  height: 120px;
  background-color: red;
}
<div class="flex-container">
  <div id="item1"></div>
  <div id="item2"></div>
</div>

https://jsfiddle.net/vL508wax/

我希望蓝色正方形居中,并且红色正方形顶部与蓝色正方形顶部齐平。

我知道可以使用 margin-top 来实现,但我认为这不是一个好的方式。是否可以直接使用 flexbox 来完成此操作?


你说“我想让蓝色正方形居中”,但是在下面的答案中看起来并不居中。你能否澄清一下问题,也许你想让它们两个都居中,同时红色在顶部? - Temani Afif
2个回答

4

由于使用flexbox布局较为困难,因此需要使用CSS网格解决方案:

.flex-container{
  height:300px;
  width:300px;
  display:grid;
  grid-auto-flow:column; /* side by side */
  grid-template-rows:100px; /* the blue height here */
  /* center everything*/
  align-content:center;
  justify-content:center;
  /**/
  background: 
    linear-gradient(green 0 0) center/100% 1px no-repeat,
    #ffeeee
}

#item1{
  width:100px;
  height:100%;
  background-color:blue;
}

#item2{
  width:120px;
  height:120px;
  background-color:red;
  transition:1s all;
}
#item2:hover {
  height:160px;
}
<div class="flex-container">
  <div id="item1">
  
  </div>
  <div id="item2">
  
  </div>
</div>


似乎Grid会是更高效的解决方案。但是通过使用align-content属性,flex也可以很好地工作。 - Michael Benjamin
@MichaelBenjamin 这个问题说需要将蓝色居中,同时将红色置于顶部。因此,我们需要先将蓝色居中,然后将红色调整到其顶部(可能不是最终的意思)。 - Temani Afif
同意弹性布局的答案没有达到所要求的精确居中。 - Michael Benjamin

2

我不确定你的使用情况,也没有进行足够的测试,但是如果总是有2个元素,你可以使用flex-wrapalign-content:center;

来实现。

.flex-container {
  height: 300px;
  width: 300px;
  display: flex;
  align-content: center;
  flex-wrap: wrap;
  justify-content: center;
  background-color: #ffeeee
}

#item1 {
  width: 100px;
  height: 100px;
  background-color: blue;
}

#item2 {
  width: 120px;
  height: 160px;
  background-color: red;
}
<div class="flex-container">
  <div id="item1"></div>
  <div id="item2"></div>
</div>


1
我总是忘记 align-content,好答案! - dippas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接