flex布局space-between 每排3个 不足三个从左到右按顺序排
时间: 2023-07-22 19:17:10 浏览: 53
要实现每排最多显示3个元素,不足三个从左到右按顺序排,可以先将 `.container` 元素的 `justify-content` 属性设置为 `flex-start`,这样所有的元素都会靠左排列。然后通过设置 `.box` 元素的 `flex` 属性来控制剩余的空间,使得最后一行的元素依次排列。最后,使用伪类 `:nth-child()` 来设置第1、4、7个元素的右边距为10px,这样每一排的元素之间保持等距。
HTML结构:
```html
<div class="container">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="box">5</div>
<div class="box">6</div>
<div class="box">7</div>
</div>
```
CSS样式:
```css
.container {
display: flex;
flex-wrap: wrap;
justify-content: flex-start;
}
.box {
width: 30%;
margin-bottom: 10px;
flex: 1 0 auto;
}
.box:nth-child(3n+1) {
margin-right: 10px;
}
.box:last-child:nth-child(n+4) {
margin-right: auto;
}
.box:last-child:nth-child(-n+3) {
margin-right: 10px;
}
```
这里同样设置了每个 `.box` 元素的宽度为30%以及下边距为10px,但是使用了 `flex: 1 0 auto;` 属性来控制剩余的空间,这样最后一行的元素会依次排列。同时,使用伪类 `:nth-child()` 来设置第1、4、7个元素的右边距为10px,同时设置最后一行的元素的右边距为自动或者10px,这样最后一行的元素会从左到右依次排列。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)