圣杯布局和双飞翼布局的共同点:
1.都是实现左右宽度固定,中间自适应
2.在dom中主内容必须第一个加载(所以要把content放在left和right前面)
3.其父元素的高度始终是由三栏中高度最高的元素
它们的实现都是在以上三个的基础上的。
1.圣杯布局
html部分:
<div class="demo"><div class="content">我是自适应的,要写在前面优先渲染</div><div class="left">左边:我是固定的</div><div class="right">右边:我是固定的</div> </div>
css部分实现思路:
1.三列布局都左浮动
2.设置content宽度为100%
3.给left元素设置margin-left:-100%;right元素设置margin-left:-200px,让left,right元素和content元素能并排显示
4.容器设置padding给左右两列预留位置,padding大小分别为左右两列的宽度
5.给left和right设置position:relative,设置left元素left:-100px(-自身宽度),right元素right:-200px(-自身宽度)
css代码如下:
.demo{padding: 0 200px 0 100px;background-color: gray;overflow: hidden;zoom: 1; } .left,.right,.content{float: left;position: relative; } .left{background-color: red;width: 100px;height: 100px;margin-left: -100%;left: -100px; } .right{background-color: bisque;width: 200px;height: 200px;margin-left: -200px;right: -200px; } .content{background-color: green;width: 100%; }
效果如下:
2.双飞翼布局
html部分
<div class="demo"><div class="content"><div class="inner-content">我是自适应的,要写在前面优先渲染</div></div><div class="left">左边:我是固定的</div><div class="right">右边:我是固定的</div> </div>
css实现思路(前三点实现同圣杯布局):
1.三列布局都左浮动
2.设置content宽度为100%
3.给left元素设置margin-left:-100%;right元素设置margin-left:-200px,让left,right元素和content元素能并排显示
4.给content内层嵌套一个div,然后给这个div设置margin值
css部分代码(标黄部分为相比圣杯布局新增部分):
.demo{/* padding: 0 200px 0 100px; */background-color: gray;overflow: hidden;zoom: 1;}.left,.right,.content{float: left;/* position: relative; */}.left{background-color: red;width: 100px;height: 100px;margin-left: -100%;/* left: -100px; */}.right{background-color: bisque;width: 200px;height: 200px;margin-left: -200px;/* right: -200px; */}.content{background-color: green;width: 100%;}.inner-content{margin: 0 200px 0 100px;}
效果如图:
总之,圣杯布局是通过父容器的内边距来实现各列的间隙,而双飞翼布局是通过新建的div的外边距隔离各列的。
另外,实现左右定宽,中间自适应的三列布局也可以使用flex布局(简单起见,没有加浏览器前缀)。
html部分:
<div class="flex-demo"><div class="content1">我是自适应的,要写在前面优先渲染</div><div class="left1">左边:我是固定的</div><div class="right1">右边:我是固定的</div></div>
css部分:
.flex-demo{display: flex;}.content1{background-color: green;flex: 1;order: 2;}.left1{background-color: red;width: 100px;height: 100px;order: 1;}.right1{background-color: bisque;width: 200px;height: 200px;order: 3;}
效果图如下: