CSS实现多列等宽的方法详解
实现方法有css与js三种方法了,下面我们一起来看看.
网页中多列等宽是很常见的布局,一般使用百分比的 width 属性即可轻松实现。
我想出了三种解决方案,下边分别介绍。
display: table-cell
第一种方法利用 display 属性的 table-cell 值,把元素变成表格,就可以等宽了。
<style type="text/css">
.box {
width: 600px;
}
.box div {
color: #FFF;
display: table-cell;
height: 150px;
}
</style>
<div class="box">
<div style="background: #666;">
<span>第1列 第1列 第1列 第1列</span>
</div>
<div style="background: #444;">
<span>第2列 第2列 第2列 第2列</span>
</div>
<div style="background: #222;">
<span>第3列 第3列 第3列 第3列</span>
</div>
<div style="background: #000;">
<span>第4列 第4列 第4列 第4列</span>
</div>
</div>
这种方法是比较好的,兼容到 IE8。
权衡兼容性和复杂程度之后我选择了这种方案。
box-flex
box-flex 属性是 CSS3 的新东西,他可以把父元素的宽度分配给子元素,就像分数一样。
假设一个容器的宽度是 1200px,里边有三个子元素。
如果三个子元素的 box-flex 属性都设置成 1,那么它们将平分 1200px,也就是每个元素会获得 400px 的宽度。
如果一个元素的 box-flex 属性设置成 2,其余的两个设置成 1,那么设置成 2 的元素将会有 600px 的宽度,设置成 1 的两个元素会有 300px 的宽度。
看到这里,就会发现 box-flex 属性实在是太好了有木有,用它实现多列等高轻而易举,而且非常好理解。
<style type="text/css">
.box {
width: 600px;
display: -webkit-box;/* 注意这里 */
}
.box:after {
content: '';
height: 0;
display: block;
clear: both;
}
.box div {
color: #FFF;
box-flex: 1;
-webkit-box-flex: 1;
-moz-box-flex: 1;
height: 150px;
float: none;
}
</style>
<div class="box">
<div style="background: #666;">
<span>第1列</span>
</div>
<div style="background: #444;">
<span>第2列</span>
</div>
<div style="background: #222;">
<span>第3列</span>
</div>
<div style="background: #000;">
<span>第4列</span>
</div>
</div>
可惜这种方法兼容性不佳,只有 IE10 和 Chrome 等浏览器支持,但这么强大的属性还是了解一下比较好。
JavaScript
最后一种方法就不是纯 CSS 了,需要使用 JS 实现,这种方法兼容性最好,支持几乎目前所有浏览器,但是比较麻烦。
<style type="text/css">
.box {
width: 600px;
}
.box:after {
content: '';
height: 0;
display: block;
clear: both;
}
.box div {
color: #FFF;
height: 150px;
float: left;
}
</style>
<script>
window.onload = function(){
var box = document.getElementById( 'box' ),
Elements = box.getElementsByTagName( 'div' ),
width = box.currentStyle ? box.currentStyle['width'] : document.defaultView.getComputedStyle( box, false )['width'];
width = parseInt( width );
for( var i = Elements.length - 1; i >= 0; i-- ){
Elements[i].style.width = width / Elements.length 'px';
};
}
</script>
<div class="box" id="box">
<div style="background: #666;">
<span>第1列</span>
</div>
<div style="background: #444;">
<span>第2列</span>
</div>
<div style="background: #222;">
<span>第3列</span>
</div>
<div style="background: #000;">
<span>第4列</span>
</div>
</div>
您可能感兴趣的文章: