flex布局一行显示多个
flex布局之一行显示4个,如果多于4个,自动换行
·
在前端开发的时候,对页面布局的时候,经常遇到固定的一行显示多个,这个经常遇到,所以我想做个记录,等到下次遇到的时候,可以直接拿来使用。
flex布局之一行显示4个,如果多于4个,自动换行,代码如下
<div style="display: flex; justify-content: space-between; flex-wrap: wrap; ">
<div class="item" style="background-color: aliceblue;"></div>
<div class="item" style="background-color: antiquewhite;"></div>
<div class="item" style="background-color: aqua;"></div>
<div class="item" style="background-color: black;"></div>
<div class="item" style="background-color: blueviolet;"></div>
<div class="item" style="background-color: chartreuse;"></div>
<div class="item" style="background-color: crimson;"></div>
</div>
<style>
.item{
color: black;
flex: 0 0 24%;
height: 30px;
text-align:center;
line-height:30px;
background-color: white;
/* 边距懒得算,css函数代替 */
margin-right: calc(4% / 3);
margin-bottom: calc(4% / 3);
}
/* 去除每行尾的多余边距 */
.item:nth-child(4n){
margin-right: 0;
}
/* 使最后一个元素的边距填满剩余空间 */
.item:last-child{
margin-right: auto;
}
</style>
效果图:
flex属性 是 flex-grow、flex-shrink、flex-basis三个属性的缩写
推荐使用简写属性,而不是单独写这三个属性。
flex-grow:定义项目的的放大比例;
- 默认为0,即 即使存在剩余空间,也不会放大;
- 所有项目的flex-grow为1:等分剩余空间(自动放大占位);
- flex-grow为n的项目,占据的空间(放大的比例)是flex-grow为1的n倍。
flex-shrink:定义项目的缩小比例;
- 默认为1,即 如果空间不足,该项目将缩小;
- 所有项目的flex-shrink为1:当空间不足时,缩小的比例相同;
- flex-shrink为0:空间不足时,该项目不会缩小;
- flex-shrink为n的项目,空间不足时缩小的比例是flex-shrink为1的n倍。
flex-basis: 定义在分配多余空间之前,项目占据的主轴空间(main size),浏览器根据此属性计算主轴是否有多余空间,
- 默认值为auto,即 项目原本大小;
- 设置后项目将占据固定空间。
calc() 函数用于动态计算长度值
- 需要注意的是,运算符前后都需要保留一个空格,例如:
width: calc(100% - 10px)
; - 任何长度值都可以使用calc()函数进行计算;
- calc()函数支持 "+", "-", "*", "/" 运算;
- calc()函数使用标准的数学运算优先级规则;
更多推荐
已为社区贡献1条内容
所有评论(0)