CSS布局之圣杯布局/双飞翼布局
📝个人主页: 💌系列专栏: 🧑💻座右铭:道阻且长,行则将至💗
圣杯布局
HTML代码
<div class="wrap"> <div class="left">left</div> <div class="center">center</div> <div class="right">right</div> </div>
步骤
- 给最外层容器wrap设置padding-left: 200px;、padding-right: 200px;
- 渲染content、left、right三个容器
-
都设置浮动float: left;,脱离文档流; 设置left和right宽度和高度:width: 200px;、height: 100px; 设置center的宽度:width: 100%;,使其充满容器;高度:height: 100px;
🌸查看效果
- 将left移动到左边空白区
-
先将left拉回第一行,使其覆盖在center的最左侧:position: relative;、margin-right: -100%;
-
将left相对于center容器向左移100%(也就是content自身的宽度)left: -200px;
- 将right移动到右边空白区
-
先将right拉回第一行:position: relative;、margin-left: -200px;
-
将right相对于自身向右移200px:left: 200px;
🌸最终效果
CSS代码
.wrap { padding-left: 200px; padding-right: 200px; } .left { position: relative; float: left; left: -200px; margin-right: -100%; width: 200px; height: 200px; background-color: pink; } .center { float: left; width: 100%; height: 200px; background-color: greenyellow; } .right { position: relative; float: left; left: 200px; margin-left: -200px; width: 200px; height: 200px; background-color: pink; }
双飞翼布局
HTML代码
<div class="wrap"> <div class="center">center</div> <div class="left">left</div> <div class="right">right</div> </div>
步骤
- 渲染content、left、right三个容器
-
都设置浮动float: left;,脱离文档流; 设置left和right宽度和高度:width: 200px;、height: 200px; 设置center的宽度:width: 100%;,使其充满容器;高度:height: 200px;
🌸查看效果
- 将left拉回第一行,使其覆盖在center的最左侧:margin-right: -100%;
- 将right拉回第一行,使其覆盖在center的最右侧:margin-left:-200px
🌸最终效果
CSS代码
.left { float: left; margin-left: -100%; width: 200px; height: 200px; background-color: pink; } .center { float: left; width: 100%; height: 200px; background-color: greenyellow; } .right { float: left; margin-left: -200px; width: 200px; height: 200px; background-color: pink; }
小结
圣杯布局和双飞翼布局实现的效果都是相同的,只是在左右容器覆盖在中间容器中时,处理的容器不同而已。圣杯布局在处理左右容器,用相对定位时要注意左右平移的方向是相反的。双飞翼布局处理中间容器时要注意内层容器的内边距。