我想知道是否有可能让 flex 元素与同一容器中较大的 flex 元素水平对齐。使用 CSS float 很容易完成,但我无法使用 flex 元素完成它。
View this JSFiddle for a flexbox example.
View this JSFiddle a float example
网格布局
<div class="flex-container">
<div class="large-flex-item">
</div>
<div class="small-flex-item">
</div>
<div class="small-flex-item">
</div>
</div>
CSS
.flex-container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
align-items: flex-start;
max-width: 500px;
margin-right: auto;
margin-left: auto;
}
.small-flex-item {
flex-basis: 33.333%;
background: #000;
padding-top: 30%;
}
.large-flex-item {
flex-basis: 66.667%;
background: #333;
padding-top: 60%;
}
最佳答案
Flexbox 不喜欢通过多列或多行扩展的 flex 元素,因为实际上 flexbox 没有网格概念。
但是,使用一些技巧,您可以实现此布局(以及 more complicated ones):
使用行布局
┌─┬─┬─┐ │1│2│3│ └─┴─┴─┘
允许使用
flex-wrap: wrap
换行。使用伪元素强制在 2 之后换行
┌─┬─┐ │1│2│ ├─┼─┘ │3│ └─┘
在 2 和 3 上使用
width: 33%
,在 1 上使用flex: 1
。┌───────────────┬─────┐ │1 │2 │ ├─────┬─────────┴─────┘ │3 │ └─────┘
将
margin-left: auto
设置为 3┌───────────────┬─────┐ │1 │2 │ └───────────────┼─────┤ │3 │ └─────┘
选择一些长度
x
将
height: x
设置为 2 和 3。将height: 2*x
设置为 1。┌───────────────┬─────┐ │1 │2 │ │ ├─────┘ │ │ └───────────────┼─────┐ │3 │ └─────┘
将
margin-bottom: -x
设置为 1:┌───────────────┬─────┐ │1 │2 │ │ ├─────┤ │ │3 │ └───────────────┴─────┘
注意 flexbox 引入
<auto
作为min-width
的新初始值。这可能会让内容迫使一些盒子变大。这会破坏布局,因此请使用min-width: 0
禁用它或将overflow
设置为visible
以外的任何值。
代码如下:
.flex-container {
display: flex;
flex-flow: row wrap;
}
.flex-item {
overflow: hidden;
}
.flex-container::after {
content: '';
width: 100%; /* Force line break */
}
.large.flex-item {
flex: 1;
height: 200px;
margin-bottom: -100px;
background: red;
}
.small.flex-item {
width: 33.333%;
height: 100px;
background: green;
}
.small.flex-item + .small.flex-item {
order: 1;
margin-left: auto;
background: blue;
}
<div class="flex-container">
<div class="large flex-item">1</div>
<div class="small flex-item">2</div>
<div class="small flex-item">3</div>
</div>
但是,修改 HTML 以获得嵌套的 flexbox 会更容易。
关于html - 在同一容器中对齐具有不同高度的 flex 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34069504/