圣杯布局和双飞翼布局是前端工程师需要日常掌握的重要布局方式。两者的功能相同,都是为了实现一个两侧宽度固定,中间宽度自适应的三栏布局。
一、圣杯布局
具体实现代码如下:
DOM结构:
<div id="header">header</div> <div id="container"> <div id="center" class="cloumn">center</div> <div id="left" class="cloumn">left</div> <div id="right" class="cloumn">right</div> </div> <div id="footer">footer</div>
注意:center必须写在left和right前面
CSS样式:
<style> /* 清楚浏览器默认样式,设置默认样式(可自定义) */ * { padding: 0; margin: 0; font-size: 28px; text-align: center; line-height: 40px; } /* 设置头部 */ #header { width: 100%; height: 40px; background-color: cornflowerblue; } /* 设置底部 */ #footer { width: 100%; height: 40px; background-color: gray; clear: both; /* 清除浮动 */ } /* 圣杯布局的第一步:设置容器,左右两边的大大小 */ #container { padding-left: 100px; padding-right: 100px; } /* 向左浮动,脱离文档流 */ #container .cloumn { float: left; } /* 设置center,宽度设为100%可达到自适应的效果*/ #center { width: 100%; height: 300px; line-height: 300px; } /* 设置left */ #left { position: relative; right: 100px; width: 100px; margin-left: -100%; /* 负外边距,结合相对定位将left放置到之前预留的位置上*/ background-color: greenyellow; height: 300px; line-height: 300px; } /* 设置righ */ #right { width: 100px; margin-right: -100px; background-color: hotpink; height: 300px; line-height: 300px; } </style>
二、双飞翼布局
具体实现代码如下:
DOM结构:
<div id="header">header</div> <div id="container" class="column"> <div id="center">center</div> </div> <div id="left" class="column">left</div> <div id="right" class="column">right</div> <div id="footer">footer</div>
CSS样式:
<style> /* 清除默认样式,自定义默认样式 */ * { padding: 0; margin: 0; font-size: 28px; text-align: center; line-height: 40px; } /* 设置头部 */ #header { width: 100%; height: 40px; background-color: cornflowerblue; } /* 设置底部 */ #footer { width: 100%; height: 40px; background-color: gray; clear: both; /* 清除浮动 */ } /* 设置容器,只包含center子元素 */ #container { width: 100%; } /* 向左浮动 */ .column { float: left; } /* 设置center,为左右两边预留位置 */ #center { margin-left: 100px; margin-right: 100px; height: 300px; line-height: 300px; } /* 设置left */ #left { width: 100px; margin-left: -100%; background-color: greenyellow; height: 300px; line-height: 300px; } /* 设置right */ #right { width: 100px; margin-left: -100px; background-color: hotpink; height: 300px; line-height: 300px; }</style>