样式优化-float 与 inline-block
2020-03-04 本文已影响0人
KIKIWS
优化背景
常见的三列式的排列布局,视觉要求区域底部无边距间距。旧代码使用float布局方式,js判断需要去除下边距的项,如下片段:
css
.item
background-color #FFFFFF
width calc(((100% - 0.24rem) / 3))
float left
margin-right 0.12rem
margin-bottom 0.12rem
border-radius 0.08rem
overflow hidden
.item:nth-of-type(3n)
margin-right 0
js
// 设置商品项特殊样式
setSpecialClass(item, idx) {
const len = this.itemList.length
item.specialClass = ''
if (this.data.componentInfoJson.col === 3 && (len % 3 === 1 || len % 3 === 2) && idx >= len - (len % 3)) {
item.specialClass = 'no-margin-bottom'
}
return item
}
优化方案
1、照常使用float布局,设置顶部间距,消除前三项的顶部间距
2、使用 display: inline-block,设置底部间距,元素的垂直对齐方式为上( vertical-align: top),消除最后三项的底部间距
使用方案2 ,原js代码删除,css如下:
.item
background-color #FFFFFF
width calc(((100% - 0.24rem) / 3))
display inline-block
vertical-align top
margin-right 0.12rem
margin-bottom 0.12rem
border-radius 0.08rem
overflow hidden
&:nth-of-type(3n)
margin-right 0
&:nth-last-child(1)
margin-bottom 0
&:nth-last-child(2)
margin-bottom 0
&:nth-last-child(3)
margin-bottom 0
float 与 inline-block
且先看使用float布局且直接消除最后三项的底部间距的表现
![](https://img.haomeiwen.com/i8433063/ed0a8d73a6d90bc3.png)