其实对于三列布局的实现,之前网上使用最多的还是这两种。它们有一个共同的优点,就是可以使主内容优先加载。当然,如果不考虑兼容,flex和grid还是优先推荐的。
我们直接上代码,代码中有详细注释:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>圣杯布局vs双飞翼布局</title>
<style>
* {
margin:0;
padding: 0;
}
section {
margin-bottom: 10px;
}
/*虽然清除了浮动,但需要注意的是负margin引发的副作用,section其实包含了left和right负margin前的内容高度*/
.clearfix:after {
display: table;
content: '.';
visibility: hidden;
clear: both;
}
</style>
</head>
<body>
<!--圣杯布局-->
<!--优点:主内容优先展示-->
<!--缺点:屏幕宽度缩太小时,样式会乱-->
<section class="holy-grail clearfix">
<style>
.holy-grail .wrap {
padding: 0 200px;
}
.holy-grail .main {
width: 100%;
float: left;
background: red;
}
.holy-grail .left {
width: 200px;
float: left;
background: green;
margin-left: -100%;
position: relative;
left: -200px;
}
/*这里设置margin-right可以代替注释的三行代码的效果*/
.holy-grail .right {
width: 200px;
float: left;
background: blue;
/*margin-left: -200px;*/
/*position: relative;*/
/*left: 200px;*/
margin-right: -200px;
}
</style>
<article class="wrap">
<div class="main">
<p>main content</p>
<p>main content</p>
<p>main content</p>
</div>
<div class="left">left content</div>
<div class="right">right content</div>
</article>
</section>
<!--双飞翼布局-->
<!--优点:主内容优先显示,兼容性好-->
<!--缺点:需要增加一层html结构-->
<section class="double-wings clearfix">
<style>
.double-wings .main {
width: 100%;
float: left;
}
.double-wings .left {
width: 200px;
float: left;
background: green;
margin-left: -100%;
}
.double-wings .right {
width: 200px;
float: left;
background: blue;
margin-left: -200px;
}
.double-wings .inner {
background: red;
margin: 0 200px;
}
</style>
<article class="wrap">
<div class="main">
<div class="inner">
<p>main content</p>
<p>main content</p>
<p>main content</p>
</div>
</div>
<div class="left">left content</div>
<div class="right">right content</div>
</article>
</section>
</body>
</html>