两个布局均有相同的目的:
两侧内容宽度固定,中间内容宽度自适应三栏布局,中间一栏最先加载、渲染出来(主要内容)、
1. 圣杯布局
1.1 起手
页面结构如下: 用一个div将三栏进行包裹
<div id="header">Header</div>
<div id="content">
<div id="center" class="column">Center</div>
<div id="left" class="column">Left</div>
<div id="right" class="column">Right</div>
</div>
<div id="footer">Footer</div>
初始css:
- 给center设置
width: 100% - left、right定宽:
200px、100px
* {
box-sizing: border-box;
}
div {
text-align: center;
}
#header {
background-color: #f1f1f1;
}
#content #center {
background-color: #ddd;
width: 100%;
}
#content #left {
background-color: orange;
width: 300px;
}
#content #right {
background-color: green;
width: 200px;
}
#content .column {
}
#footer {
background-color: #f1f1f1;
}
效果如下
1.2 设置浮动
给三栏均设置浮动
#content .column {
float: left;
}
可以看到footer受到了影响
为footer设置
clear: both
#footer {
background-color: #f1f1f1;
clear: both;
}
1.3 content设置左右padding
#content {
padding-left: 300px;
padding-right: 200px;
}
1.4 调整left位置
先使用负maring-left调整位置,设置margin-left: -100%;
这里涉及到margin-left的百分比是以哪个元素作为标准,在 MDN中有如下描述
百分比值
<percentage>最近的块容器的宽度 width .
因此left的 margin-left 百分比,是以 center 的width作为基准
#content #left {
background-color: orange;
width: 300px;
margin-left: -100%;
}
此时 left 左边缘与 center 左边缘重叠,我们需要再做调整,将Left继续左移
使用 position: relative; 与 right 来实现,right的值为left的宽度
#content #left {
position: relative;
background-color: orange;
width: 300px;
right: 300px;
margin-left: -100%;
}
1.5 调整right位置
设置 margin-right, 值为负的right宽度
#content #right {
background-color: green;
width: 200px;
margin-right: 100px;
}
2. 双飞翼布局
2.1 起手
页面结构如下:main部分中间多出一个div,main-wrpper
<div id="main" class="column">
<div id="main-wrapper">Main</div>
</div>
<div id="left" class="column">Left</div>
<div id="right" class="column">Right</div>
初始css:
- 给center设置
width: 100% - left、right定宽:
100px、50px
* {
box-sizing: border-box;
}
div {
text-align: center;
}
#main {
background-color: #ddd;
width: 100%;
}
#left {
background-color: orange;
width: 100px;
}
#right {
background-color: green;
width: 50px;
}
2.2 设置浮动
.column {
float: left;
/* 三栏均浮动 */
}
2.3 main-wrapper设置左右margin
左右margin分别为左右栏的宽度
#main #main-wrapper {
margin-left: 100px;
margin-right: 50px;
}
2.4 调整left位置
#left {
background-color: orange;
width: 100px;
margin-left: -100%;
}
2.5 调整right位置
同样使用margin-left,值为-100%,此时该百分比以整个 main 的宽度作为基准
#right {
background-color: green;
width: 50px;
margin-left: -50px;
}
margin-left的值为 负的 right的宽度