CSS | 聖盃佈局、雙飛翼佈局 | 自適應三欄佈局
阿新 • • 發佈:2019-12-21
聖盃佈局和雙飛翼佈局是前端工程師需要日常掌握的重要佈局方式。兩者的功能相同,都是為了實現一個兩側寬度固定,中間寬度自適應的三欄佈局
雖然兩者的實現方法略有差異,不過都遵循了以下要點:
1.兩側寬度固定,中間寬度自適應
2.中間部分在DOM結構上優先,以便先行渲染
3.允許三列中的任意一列成為最高列
4.只需要使用一個額外的<div>標籤
聖盃佈局
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>聖盃佈局</title> <style type="text/css"> .header{ height:50px; background: #666; text-align: center; } .main{ /*左右欄通過新增負的margin放到正確的位置了,此段程式碼是為了擺正中間欄的位置*/ padding:0 200px 0 180px; height:100px; } .middle{ float:left; width:100%;/*左欄上去到第一行*/ height:100px; background:blue; } .left{ float:left; width:180px; height:100px; margin-left:-100%; background:#0c9; /*中間欄的位置擺正之後,左欄的位置也相應右移,通過相對定位的left恢復到正確位置*/ position:relative; left:-180px; } .right{ float:left; width:200px; height:100px; margin-left:-200px; background:#0c9; /*中間欄的位置擺正之後,右欄的位置也相應左移,通過相對定位的right恢復到正確位置*/ position:relative; right:-200px; } .footer{ height:50px; background: #666; text-align: center; } </style> </head> <body> <div class="header">header</div> <div class="main"> <div class="middle">middle</div> <div class="left">left</div> <div class="right">right</div> </div> <div class="footer">footer</div> </body> </html>
雙飛翼佈局
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>雙飛翼佈局</title>
<style type="text/css">
.header {
height: 100px;
background: bisque;
}
.left {
width: 200px;
height: 300px;
background: coral;
float: left;
margin-left: -100%;
margin-right: -200px;
}
.center {
background: palegreen;
float: left;
width: 100%;
}
.inside{
margin-left: 200px;
margin-right: 180px;
}
.right {
width: 180px;
height: 200px;
background: darkorange;
float: left;
margin-left: -180px;
}
.footer {
height: 200px;
background: salmon;
clear: both;
}
</style>
</head>
<body>
<div class="header">header</div>
<div class="main">
<div class="center">
<div class="inside">
中間自適應區域
</div>
</div>
<div class="left">左邊固定區域</div>
<div class="right">右邊固定區域</div>
</div>
<div class="footer">footer</div>
</body>
</html>