float
实现基于纯
float
实现的三栏布局须要将中间的内容放在HTML结构的最后,不然右侧会沉在中间内容的下侧css原理:元素浮动后,脱离文档流,后面的元素受浮动影响,设置受影响元素的
margin
值便可html
两边固定宽度,中间宽度自适应。布局
利用中间元素的margin
值控制两边的间距flex
宽度小于左右部分宽度之和时,右侧部分会被挤下去flexbox
<div class="wrap"> <div class="left">左侧</div> <div class="right">右侧</div> <div class="middle">中间</div> </div> <style type="text/css"> .wrap {background: #eee; overflow: hidden; padding: 20px;} <!-- 生成BFC,计算高度时考虑浮动的元素 --> .left {width: 200px; height: 50px; float: left; background: coral;} .right {width: 120px; height: 200px; float: right; background: lightblue;} .middle {margin-left: 220px; background: lightpink; margin-right: 140px;} </style>
position
实现基于绝对定位的三栏布局:注意绝对定位的元素脱离文档流,相对于最近的已经定位的祖先元素进行定位。无需考虑HTML中结构的顺序spa
缺点:有顶部对齐问题,须要进行调整,注意中间的高度为整个内容的高度3d
<div class="wrap"> <div class="left">左侧</div> <div class="middle">中间</div> <div class="right">右侧</div> </div> <style type="text/css"> .wrap {background: lightpink;} .left {width: 200px; height: 100px; position: absolute; top: 0; left: 0; background: coral;} .right {width: 120px; height: 100px; position: absolute; top:0; right: 0; background: lightblue;} .middle {height: 50px; margin: 0 140px 0 220px; background: #555;} </style>
float
和BFC
配合圣杯布局必须将中间部分的HTML结构写在最前面,三个元素均设置向左浮动。两侧元素宽度固定,中间设置为100%;而后利用左侧元素负的
margin
值进行偏移,覆盖在中间的宽度之上;右侧的元素一样利用负的margin
值进行覆盖code
存在的问题:不能自适应高度htm
<div class="wrap"> <div class="middle"> <div class="main">中间</div> </div> <div class="left">左侧</div> <div class="right">右侧</div> </div> <style type="text/css"> .wrap {overflow: hidden;} .left {float: left; width: 200px; height: 100px; background: coral; margin-left: -100%;} .middle {float: left; width: 100%; height: 100px; background: lightblue;} .right {float: left; width: 120px; height: 100px; background: gray; margin-left: -120px;} .main {margin: 0 140px 0 220px; background: lightpink;} </style>
flex
布局flexbox
布局最简洁使用,而且没有明显缺陷。blog
仅需将容器设置为display:flex;
,盒内元素两端对其,将中间元素设置为100%
宽度便可填充空白,再利用margin
值设置边距便可
而且盒内元素的高度撑开容器的高度
<div class="wrap"> <div class="left">左侧</div> <div class="middle">中间</div> <div class="right">右侧</div> </div> <style type="text/css"> .wrap {display: flex; justify-content: space-between;} .left, .right, .middle {height: 100px;} .left {width: 200px; background: coral;} .right {width: 120px; background: lightblue;} .middle {background: #555; width: 100%; margin: 0 20px;} </style>
纯float
的三栏布局须要将中间的内容放在最后;
绝对定位的三栏布局:元素对其有点问题
圣杯布局:容器内不能撑开高度
flex
布局最好,基本没有大的缺点。
纯