使用Flexbox可以创建这个网格吗:
----------
A1 | B1
----------
A2 | B2
----------
A1和A2具有固定的宽度(50px),而B1和B2则填充剩余的空间。我不想为这些列创建包装器,因为我想在移动设备上重新排列这些单元格。
兼容性:IE 11+ 和所有现代浏览器。 Safari 可以使用 -webkit-
前缀。
这里有两个主角:
容器的 display: flex
和 flex-wrap: wrap
属性。其中 "wrap" 值允许容器内容必要时换行。
flex
缩写 属性:
[flex 属性的初始值为] 其长手属性的初始值连接:
- flex-grow: 0
- flex-shrink: 1
- flex-basis: auto
在我们的例子中,我们使用:
容器 div 上的 display: flex
和 flex-wrap: wrap
可调整大小的两个 div 上的 flex: 1 1 calc(100% - 50px)
。这会让 div 的默认宽度为 100% 减去固定单元格的 50px。虽然从技术上讲它可以增长和缩小,但由于它设置为百分比,因此它将重新调整大小。
固定单元格的 flex: 0 0 50px
。这会让 div 的默认宽度为 50px,然后不会增长或缩小。
.flex-grid {
display: flex;
flex-wrap: wrap;
height: 500px;
}
.grid-item {
flex: 1 1 calc(100% - 50px);
background: #F90;
border-top: solid 1px #000;
}
.grid-item:nth-child(odd) {
background: #F00;
flex: 0 0 50px;
}
<div class="flex-grid">
<div class="grid-item">
A1
</div>
<div class="grid-item">
B1
</div>
<div class="grid-item">
A2
</div>
<div class="grid-item">
B2
</div>
</div>
使用宽度为calc(100% - 50px)
的值来设置B1和B2的宽度。
.container {
display: flex;
flex-direction: column;
flex-wrap: wrap;
width: 40%;
height: 100px;
max-height: 100px;
border: 1px solid green;
}
.container div:nth-child(-n + 2) {
background: yellow;
width: 50px;
height: 50px;
}
.container div:nth-child(n + 3) {
background: aqua;
height: 50px;
width: calc(100% - 50px);
}
<div class="container">
<div>A1</div>
<div>A2</div>
<div>B1 - Where B1&B2 fill the remaining space</div>
<div>B2 - Where B1&B2 fill the remaining space</div>
</div>