1,问题描述
需求如下:
- flex 布局,容器
padding: 12px;
- 一行2个 item,item 间距8px(最后一行
margin-bottom: 0
),item 高度自适应。
实现
<template>
<ul class="box">
<li v-for="n in 5" class="item">{{ n }}</li>
</ul>
</template>
<style lang="scss">
.box {
display: flex;
flex-wrap: wrap;
padding: 12px;
background-color: bisque;
}
.item {
width: calc((100% - 8px) / 2);
margin-bottom: 8px;
background-color: salmon;
&:nth-child(odd) {
margin-right: 8px;
}
&:nth-last-child(-n + 2) {
margin-bottom: 0;
}
}
</style>
当遍历偶数个时,没有任何问题。
当遍历奇数个时,会发现倒数第2个被拉长了
2,原因分析
有2个原因共同导致的
- 倒数第2个(第4个)的 item
margin-bottom: 0;
这让下面产生了8px的空间
&:nth-last-child(-n + 2) {
margin-bottom: 0;
}
- 容器
align-items: stretch;
的默认值效果。
默认值特点:如果 item 未设置高度或设为auto,item 将等比例拉伸占满整个容器的高度。
如果 item 设置了高度,则按照设置的高度值渲染,而非拉伸。
因为容器的高度是自适应的,所以所有的 item 已经占满整个容器的高度。对于倒数第2个 item来说,其下方还有 8px 的空间,所以高度就被拉长了 8px。
如果容器高度固定(数值较大)比如300px,所有 item 都会被拉伸:
3,解决方案
设置容器 align-items: flex-start
:item 与纵轴的起点对齐。
另外,如果容器高度固定(数值较大)比如300px,也设置了align-items: flex-start
,那就会变成这样:
解决方法和原理看我的 这篇文章
以上。
参考: