今天看到一个非常有意思的问题,怎样实现多列等高,特以此文记录一下:
1.使用margin-bottom&padding-bottom正负相抵
代码如下
<ul class="Article">
<li class="js-article-item">
<p>
露从今夜白 月是故乡明露从今夜白 月是故乡明露从今夜白 月是故乡明
露从今夜白 月是故乡明露从今夜白 月是故乡明露从今夜白 月是故乡明
露从今夜白 月是故乡明露从今夜白 月是故乡明露从今夜白 月是故乡明
露从今夜白 月是故乡明露从今夜白 月是故乡明露从今夜白 月是故乡明
</p>
</li>
<li class="js-article-item">
<p>
露从今夜白 月是故乡明露从今夜白 月是故乡明露从今夜白 月是故乡明
露从今夜白 月是故乡明露从今夜白 月是故乡明露从今夜白 月是故乡明
</p>
</li>
<li class="js-article-item">
<p>露从今夜白 月是故乡明露从今夜白 月是故乡明</p>
</li>
</ul>
样式代码:
.Article {
overflow: hidden;
}
.Article>li {
float: left;
margin: 0 10px -9999px 0;
padding-bottom: 9999px;
background: #4577dc;
width: 200px;
color: #fff;
}
.Article>li>p {
padding: 10px;
}
元素设置的padding-bottom尽可能大一些,并且需要设置一样大小的margin-bottom负值去抵消padding-bottom撑大的区域,正负一抵消,对于页面布局不会有影响。另外的话还需要设置父元素overflow:hidden把子元素多出来的色块背景隐藏掉。
结果如下:
2.使用table-cell实现
因为表格中table-cell默认等高
.Article {
display: table;
width: 100%;
table-layout: fixed;
}
.Article>li {
display: table-cell;
width: 200px;
border-left: solid 5px currentColor;
border-right: solid 5px currentColor;
color: #fff;
background: #4577dc;
}
.Article>li>p {
padding: 10px;
}
结果:
3、flex布局
.Article {
display: flex;
}
.Article>li {
flex: 1;
border-left: solid 5px currentColor;
border-right: solid 5px currentColor;
color: #fff;
background: #4577dc;
}
.Article>li>p {
padding: 10px;
}
flex中的伸缩项目默认为拉伸为父元素的高度,同样可以实现等高效果。在pc端兼容性不是很好,在ie9以及ie9以下不支持。
4、grid布局
.Article {
display: grid;
grid-auto-flow: column;
grid-gap: 20px;
}
.Article>li {
border-left: solid 5px currentColor;
border-right: solid 5px currentColor;
color: #fff;
background: #4577dc;
}
.Article>li>p {
padding: 10px;
}
grid布局的缺点和flex一样,pc端兼容性不是很好,ie9以及ie9以下不支持。
5、js计算
.Article>li {
float: left;
border: solid 5px #fff;
width: 33%;
color: #fff;
font-size: 16px;
background: #4577dc;
}
.Article>li>p {
padding: 10px;
}
jQuery( document ).ready(function() {
setEqualheight();
});
jQuery(window).resize(function() {
jQuery('.js-article-item').css('height','auto');
setEqualheight();
});
function setEqualheight() {
var height = jQuery(".js-article-item").map(function() {
return jQuery(this).height();
}).get();
jQuery(".js-article-item").height( Math.max.apply(null, height) );
}