導(dǎo)讀:
- 主要是最近在簡書上看到了相關(guān)文章覺得確實比較重要登馒,就分出來寫一下,主要說明見代碼注釋馁痴。
1.圣杯布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
text-align: center;
}
.header, .footer {
background-color: skyblue;
height: 60px;
line-height: 60px;
}
.container {
overflow: hidden;
padding: 0 100px;
}
.main {
width: 100%;
background-color: rgba(255,0,0,0.5);
height: 100px;
line-height: 100px;
float: left;
}
.left {
background-color: rgba(0,255,0,0.5);
width: 100px;
height: 100px;
line-height: 100px;
float: left;
margin-left: -100%;
position: relative;
left: -100px;
}
.right {
background-color: pink;
width: 100px;
height: 100px;
line-height: 100px;
float: left;
margin-left: -100px;
position: relative;
right: -100px;
}
</style>
</head>
<body>
<!-- 圣杯布局 -->
<div class="header">header</div>
<div class="container"> <!-- 利用左右內(nèi)邊距給左右兩個盒子留位置谊娇,overflow清浮動 -->
<div class="main">main</div> <!-- 左浮,寬度100%罗晕,實現(xiàn)中間盒子自適應(yīng)寬度 -->
<div class="left">left</div> <!-- 左浮济欢,寬度100px,通過margin-left:-100%使自己處于跟main盒子一行小渊,相對定位占據(jù)container內(nèi)邊距留出的左邊位置 -->
<div class="right">right</div> <!-- 左浮法褥,寬度100px,通過margin-left:-100px使自己處于跟main盒子一行酬屉,相對定位占據(jù)container內(nèi)邊距留出的右邊位置 -->
</div>
<div class="footer">footer</div>
</body>
</html>
-
整體效果:
圣杯布局
2.雙飛翼布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
text-align: center;
}
.header, .footer {
background-color: skyblue;
height: 60px;
line-height: 60px;
}
.container {
overflow: hidden;
}
.main {
width: 100%;
background-color: rgba(255,0,0,0.5);
height: 100px;
line-height: 100px;
float: left;
}
.inner-main {
margin-left: 100px;
margin-right: 100px;
}
.left {
background-color: rgba(0,255,0,0.5);
width: 100px;
height: 100px;
line-height: 100px;
float: left;
margin-left: -100%;
}
.right {
background-color: pink;
width: 100px;
height: 100px;
line-height: 100px;
float: left;
margin-left: -100px;
}
</style>
</head>
<body>
<!-- 雙飛翼布局 -->
<div class="header">header</div>
<div class="container"> <!-- overflow清浮動 -->
<div class="main"> <!-- 左浮半等,寬度100%,實現(xiàn)中間盒子自適應(yīng)寬度 -->
<div class="inner-main">main</div> <!-- 使用margin來取消左右盒子移上來覆蓋的地方 -->
</div>
<div class="left">left</div> <!-- 左浮呐萨,寬度100px杀饵,通過margin-left:-100%使自己處于跟main盒子一行 -->
<div class="right">right</div> <!-- 左浮,寬度100px谬擦,通過margin-left:-100px使自己處于跟main盒子一行 -->
</div>
<div class="footer">footer</div>
</body>
</html>
-
整體效果:
雙飛翼布局
總結(jié):
其實兩種布局最終實現(xiàn)的效果是差不多的切距,主要是實現(xiàn)的思路有所不同:
- 圣杯布局通過設(shè)置 container 的 padding 來為左右欄留出位置,而雙飛翼布局是在中間欄增加子元素惨远,通過內(nèi)層子元素的 margin 來為左右欄留出位置(注意: 雙飛翼布局中 width 和 float 屬性都是設(shè)置在外層 div 上的)谜悟。
- 圣杯布局中為了使得左右欄分布在最左和最右需要同時使用負(fù) margin 和相對定位實現(xiàn),而雙飛翼布局中不需要使用相對定位北秽。