在前端开发中,三列布局中左右两侧列宽度固定、中间列宽度自适应一般分为两种,圣杯布局(Holy Grail Layout)和双飞翼布局(Double Wing Layout)。两者都是用来实现三列布局,左右侧固定宽度,中间自适应并且中间列在文档流中优先渲染。以下是两种布局的详细介绍和代码示例:
圣杯布局(Holy Grail Layout):
代码如下:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style type="text/css">.wrapper{/* padding简写[上 右 下 左] */padding: 0 150px 0 200px;}.wrapper:after{display: table;content: '';clear: both;}.column{float: left;height: 200px;}.center{background-color: red;width: 100%;}.left{background-color: blue;width: 200px;position: relative;margin-left: -100%;right: 200px;}.right{background-color: green;width: 150px;margin-right: -150px;}</style> </head> <body><!-- 外层div --><div class="wrapper"><!-- 中间列自适应 --><div class="center column">center</div><!-- 左侧列固定宽度 --><div class="left column">left</div><!-- 右侧列固定宽度 --><div class="right column">right</div></div> </body> </html>
圣杯布局实现三列布局,左右列固定宽度中间列自适应,其原理是通过相对定位和负边距来实现侧边栏的定位。
双飞翼布局(Double Wing Layout):
代码如下:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style type="text/css">.wrapper{background-color: red;width: 100%;}.column{float: left;height: 200px;}.center{/* margin简写[上 右 下 左] */margin: 0 150px 0 200px;}.left{width: 200px;background-color: blue;margin-left: -100%;}.right{width: 150px;background-color: green;margin-left: -150px;}</style> </head> <body><!-- 中间列自适应 --><div class="wrapper column"><div class="center">center</div></div><!-- 左侧列固定宽度 --><div class="left column">left</div><!-- 右侧列固定宽度 --><div class="right column">right</div> </body> </html>
圣杯布局实现三列布局,左右列固定宽度中间列自适应,其原理是通过使用嵌套的div元素
来实现侧边栏的定位,以及使用负外边距将主内容区域撑开。