我想知道是否可以将柔性物品水平对齐到同一容器中较大的柔性物品。使用CSS浮动它很容易实现,但我还没有能够使用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%;
}
答案 0 :(得分:12)
Flexbox不喜欢通过多个列或行扩展的flex项目,因为实际上flexbox没有网格概念。
但是,使用一些技巧,您可以实现此布局(以及more complicated ones):
使用行布局
flex-wrap: wrap
允许使用┌─┬─┐
│1│2│
├─┼─┘
│3│
└─┘
换行。
使用伪元素在2
之后强制换行width: 33%
在2和3上使用flex: 1
,在{1>}上使用┌───────────────┬─────┐
│1 │2 │
├─────┬─────────┴─────┘
│3 │
└─────┘
。
margin-left: auto
将┌───────────────┬─────┐
│1 │2 │
└───────────────┼─────┤
│3 │
└─────┘
设为3
x
选择一些height: x
将height: 2*x
设置为2和3.将┌───────────────┬─────┐
│1 │2 │
│ ├─────┘
│ │
└───────────────┼─────┐
│3 │
└─────┘
设置为1。
margin-bottom: -x
将┌───────────────┬─────┐
│1 │2 │
│ ├─────┤
│ │3 │
└───────────────┴─────┘
设为1:
auto
注意,flexbox引入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>
Begin Transaction
但是,为了拥有嵌套的flexbox,修改HTML会更容易。
答案 1 :(得分:3)
您可以通过嵌套Flex容器来实现布局。
<强> HTML 强>
<div class="flex-container">
<div class="large-flex-item"></div><!-- flex item #1 -->
<div class="flex-container-inner"><!-- flex item #2 & nested flex container -->
<div class="small-flex-item"></div><!-- this flex item and sibling will align... -->
<div class="small-flex-item"></div><!-- ... in column next to .large-flex-item -->
</div>
</div>
<强> CSS 强>
.flex-container {
display: flex;
width: 500px;
margin-right: auto;
margin-left: auto;
}
.large-flex-item {
flex-basis: 66.667%;
height: 200px;
background: #333;
}
.flex-container-inner {
display: flex;
flex-direction: column;
flex-grow: 1;
}
.small-flex-item {
flex-basis: 100%;
height: 100px;
background: #000;
}