css - 如何在 flex 容器中排列两个居中 div 的顶部?

标签 css flexbox

这是我的代码示例:

.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/

我希望蓝色方 block 居中,红色方 block 的顶部与蓝色方 block 的顶部齐平。

我知道我可以使用 margin-top 来做到这一点,但我认为这不是一个好方法。我可以直接用 flexbox 做这个吗?

最佳答案

CSS 网格解决方案,因为使用 flexbox 会很困难:

.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>

关于css - 如何在 flex 容器中排列两个居中 div 的顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66245083/

相关文章:

css - Internet Explorer 和 Chrome : table-hover not displayed properly

java - 单击链接时需要禁用表

css - 在条件内设置变量

css - 柔性 : When text too long break into new line

html - 删除 mouseleave 上的 css3 过渡

javascript - 无法读取 null 的属性 'length' - 使用 css 显示 block (选择/onchange)

ios - 显示 : flex? 的 iOS 渲染错误

css - 如何使用 flex 放下按钮?

html - 如何在 flex 元素(单元格)中居中图像

html - 卡列不能在 Firefox 中并排工作