如何动态实现 2个单元格的时候各占一半 3个单元格的时候第一个单元格占1半 剩下的两个各占四分之一呢
时间: 2023-11-27 18:52:37 浏览: 30
可以使用CSS中的flexbox来实现动态布局。对于两个单元格,可以使用`flex: 1 1 50%;`来实现各占一半的效果,其中`flex: 1 1`表示弹性因子为1(即等分剩余空间),`50%`表示占据50%的宽度。
对于三个单元格,可以将父元素设置为`display: flex`,然后使用`flex: 1 1 50%`来让第一个单元格占据一半的宽度,另外两个单元格使用`flex: 1 1 25%`来占据四分之一的宽度。
具体实现代码如下:
```html
<div class="container">
<div class="item">单元格1</div>
<div class="item">单元格2</div>
</div>
<div class="container">
<div class="item">单元格1</div>
<div class="item">单元格2</div>
<div class="item">单元格3</div>
</div>
```
```css
.container {
display: flex;
}
.container .item {
flex: 1 1 50%; /* 两个单元格各占一半 */
}
.container:nth-child(2) .item:first-child {
flex: 1 1 50%; /* 第一个单元格占一半 */
}
.container:nth-child(2) .item:not(:first-child) {
flex: 1 1 25%; /* 剩下的两个单元格各占四分之一 */
}
```