圣杯布局和雙飛翼布局
在如今的網(wǎng)頁(yè)中我們經(jīng)撤谷耄可以看到左、中肛真、右三列谐丢,其中左右兩列寬度固定,中間寬度自適應(yīng)的布局方式蚓让,如下圖乾忱。圣杯布局和雙飛翼布局就是這種三列布局的兩種實(shí)現(xiàn)方式。
圣杯布局和雙飛翼布局的實(shí)現(xiàn)都利用了以下兩個(gè)技術(shù):
1历极、float:浮動(dòng)窄瘟,利用浮動(dòng)可以使元素脫離文檔流,從而讓塊級(jí)元素在同一行排列趟卸。
2蹄葱、負(fù)margin:在left 和 top方向上的負(fù)margin值可以將元素自身向相應(yīng)方向位移。
圣杯布局
html
<header>
<h1 style="text-align: center;">這是一個(gè)三列布局</h1>
</header>
<main>
<div class="center"><p>center</p></div>
<div class="left"><p>這里是左邊部分</p></div>
<div class="right"><p>這里是右邊部分</p></div>
</main>
<footer>
<footer style="text-align: center;"><h2>footer</h2></footer>
</footer>
css
main{
padding: 0 300px;
}
main::after{
content: "";
display: block;
clear: both;
}
main div{
float: left;
}
.center{
width: 100%;
background-color: blue;
}
.left{
width: 300px;
background-color: red;
margin-left: -100%;
position: relative;
left: -300px;
}
.right{
width: 300px;
background-color: yellow;
margin-left: -300px;
position: relative;
left: 300px;
}
雙飛翼布局
html
<header>
<h1 style="text-align: center;">這是一個(gè)三列布局</h1>
</header>
<main>
<div class="center">
<div class="center-content">
<p>center</p>
</div>
</div>
<div class="left">
<p>這里是左邊部分</p>
</div>
<div class="right">
<p>這里是右邊部分</p>
</div>
</main>
<footer>
<footer style="text-align: center;">
<h2>footer</h2>
</footer>
</footer>
css
main::after {
content: "";
display: block;
clear: both;
}
main > div {
float: left;
}
.center {
width: 100%;
}
.center-content{
margin: 0 300px;
background-color: blue;
overflow:auto;
}
.left {
width: 300px;
background-color: red;
margin-left: -100%;
}
.right {
width: 300px;
background-color: yellow;
margin-left: -300px;
}
區(qū)別
不仔細(xì)看锄列,會(huì)感覺(jué)這兩個(gè)布局不是一樣的嗎图云?沒(méi)有發(fā)現(xiàn)差異的話不妨先仔細(xì)看一下上面的代碼并思考一下差異。
其實(shí)他們的區(qū)別在于邻邮,使center部分的內(nèi)容不被left和right部分給遮擋的處理方式竣况。
1、圣杯布局是在父容器main上加在左右padding(左右部分的寬度 px)筒严,再利用定位調(diào)整left 和 right的位置丹泉。
2、雙飛翼布局是通過(guò)在center部分種添加一個(gè)center子塊(center-content)讓它的左右margin 等于左右部分的寬度鸭蛙。
ps:圣杯布局在center的寬度小于left right部分的寬度時(shí)嘀掸,布局會(huì)亂。
最后
在flex和grid 布局出現(xiàn)的今天實(shí)現(xiàn)類似的三列布局已經(jīng)非常簡(jiǎn)單规惰,但是如果考慮到兼容性問(wèn)題的話睬塌,基于浮動(dòng)的這兩種布局方式還是需要了解的。最后謝謝各位小伙伴閱讀文章歇万,如有錯(cuò)誤還望指出揩晴。