1.首先,什么是圣杯布局?
圣杯布局满足以下特点:
- 两侧宽度固定,中间宽度自适应。
- 中间部分在DOM结构上优先,以便先行渲染。
- 允许三列中的任意一列成为最高列。
- 只需要使用一个额外的
div
标签。
2.如何实现?
- 使用弹性盒子
注意:因为中间部分要先行渲染,所以,在代码上应该是放在.wrapper
父元素第一个子元素的位置上的。为了让中间部分在视觉上显示在中间,这里使用了css的order
属性。该属性的作用就是:使得元素在视觉上改变位置,不影响元素的实际结构。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>圣杯布局</title>
<style>
*{
padding: 0;
margin: 0;
color: #fff;
font-size: 19px;
}
.header {
background: blue;
}
.footer{
background: coral;
}
.wrapper{
display: flex;
}
.content {
flex: 1;
background: #ff2d25;
order: 2;
}
.left {
width: 200px;
background: green;
order: 1;
flex-shrink: 0;
}
.right {
width: 250px;
background: #5e79ff;
order: 3;
flex-shrink: 0;
}
</style>
</head>
<body>
<div class="header">头部</div>
<div class="wrapper">
<div class="content">中间</div>
<div class="left">左边</div>
<div class="right">右边</div>
</div>
<div class="footer">底部</div>
</body>
</html>
- 都使用
float:left
。这里的重点就是负外边距
的运用(negative margin
)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>圣杯布局</title>
<style>
*{
padding: 0;
margin: 0;
color: #fff;
font-size: 19px;
}
.header {
background: blue;
}
.wrapper{
padding: 0 250px 0 200px;
overflow: hidden;
}
.content {
background: #ff2d25;
float: left;
width: 100%;
}
.left {
width: 200px;
background: green;
float: left;
margin-left: -100%;
left: -200px;
position: relative;
}
.right {
width: 250px;
background: #5e79ff;
float: left;
margin-left: -250px;
left: 250px;
position: relative;
}
.footer{
background: #28ff31;
clear: both;
}
</style>
</head>
<body>
<div class="header">头部</div>
<div class="wrapper">
<div class="content">中间</div>
<div class="left">左边</div>
<div class="right">右边</div>
</div>
<div class="footer">底部</div>
</body>
</html>
- 绝对定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>圣杯布局</title>
<style>
*{
padding: 0;
margin: 0;
color: #fff;
font-size: 19px;
}
.header {
background: blue;
}
.wrapper{
padding: 0 250px 0 200px;
position: relative;
}
.content {
background: #ff2d25;
}
.left {
width: 200px;
background: green;
left: 0;
top:0;
position: absolute;
}
.right {
width: 250px;
background: #5e79ff;
right: 0;
top:0;
position: absolute;
}
.footer{
background: #28ff31;
clear: both;
}
</style>
</head>
<body>
<div class="header">头部</div>
<div class="wrapper">
<div class="content">中间</div>
<div class="left">左边</div>
<div class="right">右边</div>
</div>
<div class="footer">底部</div>
</body>
</html>