共同点:解决需求“三栏布局,两边固定宽度,中间自适应,且主要内容首要显示”
不同点:在解决中间栏内容被遮挡问题上,思路不同
共同特点:
1.中间栏自适应,两边固定宽度
2.主要内容优先渲染显示
1.圣杯布局
1.1页面html结构
<body>
<div class="container">
<section class="center">CENTER</section>
<section class="left">LEFT</section>
<section class="right">RIGHT</section>
</div>
</body>
优先展示center栏,所以要放第一
思路
1.两边定宽
* {
margin: 0;
padding: 0;
}
.container {
width: 100vw;
background-color: black;
}
section {
color: wheat;
height: 25vh;
}
.center {
background-color: red;
}
.left {
background-color: rgb(88, 139, 12);
width: 200px;
}
.right {
background-color: blue;
width: 200px;
}
目前页面
圣杯1.png
2.让三个盒子同行,设置浮动
section {
color: wheat;
height: 25vh;
+ float: left
}
目前页面
圣杯2.png
出现问题:
1.子盒子全浮动,父盒子高度坍缩 解决:父盒子设置overflow:hidden
.container {
+ overflow: hidden;
width: 100vw;
background-color: black;
}
目前页面
圣杯3
3.中间自适应,中间栏设置 width:100%
.center {
background-color: red;
+ width: 100%;
}
目前页面
圣杯4
4.此时左右栏被挤到了下面,所以要用负边距回到中间栏所在行,左栏要左移父盒子宽度的100%,右栏要左移自身宽度的100%
.left {
background-color: rgb(88, 139, 12);
width: 200px;
+ margin-left: -100%;
}
.right {
+ margin-left: -200px;
background-color: blue;
width: 200px;
}
当前页面
圣杯5
出现问题:很显然,中间栏被遮挡了 解决:父盒子设置成border-box,并且设置内边距,将内容挤到中间,再将两边栏向左右移
.container {
overflow: hidden;
width: 100vw;
background-color: black;
+ box-sizing: border-box;
+ padding: 0 200px;
}
.left {
+ position: relative;
+ left: -200px;
background-color: rgb(88, 139, 12);
width: 200px;
margin-left: -100%;
}
.right {
+ position: relative;
+ right: -200px;
margin-left: -200px;
background-color: blue;
width: 200px;
}
当前页面,完成!
圣杯7
注意:当父盒子宽度小于左右两边栏宽度,即放不下左右边栏时,页面发送变形
变形
圣杯布局总结:用父盒子的padding将中间栏挤到中间,并腾出地方给两边栏
双飞翼布局
html结构
<body>
<div class="container">
<section class="center">
<div class="content">CENTER</div>
</section>
<section class="left">LEFT</section>
<section class="right">RIGHT</section>
</div>
</body>
原理与圣杯布局基本相同,只不过是给中间栏外包了一层,用外面的新层代替父盒子创建padding,此时两边栏不用再左右移动自身宽度
.center {
background-color: red;
width: 100vw;
padding: 0 200px;
box-sizing: border-box;
}
而且双飞翼没有变形问题,建议使用
双飞翼全部代码
<style>
* {
margin: 0;
padding: 0;
}
.container {
overflow: hidden;
width: 100vw;
background-color: black;
}
section {
float: left;
color: wheat;
height: 25vh;
}
.center {
background-color: red;
width: 100vw;
padding: 0 200px;
box-sizing: border-box;
}
.left {
margin-left: -100%;
background-color: rgb(88, 139, 12);
width: 200px;
}
.right {
margin-left: -200px;
background-color: blue;
width: 200px;
}
</style>
<body>
<div class="container">
<section class="center">
<div class="content">CENTER</div>
</section>
<section class="left">LEFT</section>
<section class="right">RIGHT</section>
</div>
</body>