实现这样一个两列布局:左边宽度固定(200px),右边自适应。
<div class = "block">
<div class = "left">固定宽度</div>
<div class = "right">自适应</div>
</div>
-
方法一
解析:左边设置了浮动,脱离了正常文档流。右边向左靠拢,加上左外边距为左边留宽。
.left{ width:200px; height:300px; background-color:red; float:left; } .right{ height:300px; background-color:blue; width: 100%; padding-left: 200px; box-sizing: border-box; }
-
方法二
解析:将两个块级元素设为行块,但这样会产生一个间隙,由设置父元素字号为0解决掉;接下来设置右边的宽度为100%以及其内外左边距 ;最后为了解决左边被覆盖的问题,为左边设置一个相对定位。
这里之所以设置相对定位而不是z-index的原因是:z-index对于正常流中的元素并不起作用,而具有position属性且属性值不为static的元素的层级高于相邻的不具有position的元素。
.block{ font-size:0; } .left{ width:200px; height:300px; background-color:red; display:inline-block; font-size:1rem; position:relative; } .right{ height:300px; background-color:blue; display:inline-block; width:100%; margin-left:-200px; padding-left:200px; box-sizing:border-box; font-size:1rem; }
-
方法三
解析:左边的position值为relative,脱离文档流;右边与外层div的position子绝父相。再设置左边层级高于右边即可。
.block{ position: relative; } .left{ width:200px; height:300px; background-color:red; position: relative; z-index: 1; } .right{ height:300px; background-color:blue; position: absolute; right: 0; top: 0; width: 100%; padding-left: 200px; box-sizing: border-box; }
-
方法四
解析: 利用flex布局在父盒子宽度不够时会自动压缩子盒子的特性。设置左边不参与压缩,右边被压缩。
.block{ display:flex; } .left{ width:200px; height:300px; background-color:red; flex-shrink: 0; } .right{ height:300px; background-color:blue; width: 100%; }
-
方法五
解析: 右边触发BFC,将不与左侧发生重叠。右边盒子默认100%。
.left{ width:200px; height:300px; background-color:red; float:left; } .right{ height:300px; background-color:blue; overflow:hidden; }
-
方法六
.block{ display: grid; grid-template-rows: 200px; grid-template-columns: 200px auto; width:100%; } .left{ background: red; } .right{ background: blue; }
-
方法七
.block{ display: table; width:100%; } .left{ display: table-cell; height: 200px; width: 200px; background: red; } .right{ display: table-cell; height: 200px; background: blue; }