双飞翼布局和圣杯布局是前端工程师需要日常掌握的重要布局方式。两者的功能相同,都是为了实现一个两侧宽度固定,中间宽度自适应的三栏布局。(中间先加载渲染)
双飞翼的布局与实现原理(推荐使用双飞翼布局)
双飞翼布局:对圣杯布局(使用相对定位,对以后布局有局限性)的改进,消除相对定位布局
原理:主体元素上设置左右边距,预留两翼位置。左右两栏使用浮动和负边距归位,消除相对定位。
双飞翼布局代码:
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title></title><style type="text/css">.header,.footer{height: 200px;width: 100%;background-color: #00FFFF;}.content,.left,.right{height: 200px;float: left;}.container::after{content: "";display: block;clear: both;}.content{width: 100%;background-color: pink;}.left{width: 300px;background-color: red;margin-left: -100%;}.right{width: 300px;background-color: grey;margin-left: -300px;}.center{height: 200px;margin-left: 300px;margin-right:300px ;}body{min-width: 600px;}</style></head><body><div class="header">头部</div><div class="container"><div class="content"><div class="center">中间</div></div><div class="left">左边</div><div class="right">右边</div></div><div class="footer">尾部</div></body>
</html>
运行效果:
圣杯布局的实现原理
要求:三列布局;中间主体内容前置,且宽度自适应;两边内容定宽
好处:重要的内容放在文档流前面可以优先渲染
原理:利用相对定位、浮动、负边距布局,而不添加额外标签
圣杯布局代码:
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title></title><style type="text/css">.header,.footer{height: 200px;width: 100%;background-color: #00FFFF;}.center,.left,.right{height: 200px;float: left;}.left,.right{width: 300px;}.center{width: 100%;background-color: pink;}.left{background-color: red;margin-left: -100%;position: relative;left: -300px;}.right{background-color: lawngreen;margin-left: -300px;position: relative;left: 300px;}.container::after{content: "";display: block;clear: both;}.container{padding-left: 300px;padding-right: 300px;}body{min-width: 900px;}</style></head><body><div class="header">头部</div><div class="container"><div class="center">中间</div><div class="left">左边</div><div class="right">右边</div></div><div class="footer">尾部</div></body>
</html>
运行效果: