圣杯布局基本介绍
圣杯布局达到视觉效果为,两边两栏宽度固定,中间栏宽度自适应。在HTML结构上中间栏在最前面保证了最先渲染中间提升性能(因为这种布局比较老,我认为在现代浏览器中这点儿性能优化效果并不是很大),并且兼容性良好。
浮动法
核心:中间三列设置float:left
,清除父元素#content
的浮动影响,并给#content
设置padding
。调整#middle
的宽度width:100%
,通过margin-left
和相对定位的方式,调整#left
和#right
,使其位于#middle
的两侧
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>浮动</title>
<style>
*{
margin: 0;
padding: 0;
}
#header,#footer{
background-color: gray;
}
#content{
overflow: hidden;
padding: 0 200px;
}
#middle,#left,#right{
float: left;
height: 200px;
}
#middle{
width: 100%;
background-color: skyblue;
}
#left,#right{
background-color: pink;
width: 200px;
}
#left{
margin-left: -100%;
position: relative;
left: -200px;
}
#right{
margin-left: -200px;
position: relative;
right: -200px;
}
</style>
</head>
<body>
<div id="header">header</div>
<div id="content">
<div id="middle">middle</div>
<div id="left">left</div>
<div id="right">right</div>
</div>
<div id="footer">footer</div>
</body>
</html>
绝对定位法
核心:父元素#content
设置相对定位,#left
和#right
设置绝对定位。通过绝对定位的方式让#left
和#right
位于#middle
的两侧,调整#middle
的margin
使其内容不被遮挡
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>绝对定位法</title>
<style>
*{
margin: 0;
padding: 0;
}
#header,#footer{
background-color: gray;
}
#content{
position: relative;
}
#middle{
background-color: skyblue;
margin: 0 200px;
height: 200px;
}
#left,#right{
background-color: pink;
width: 200px;
height: 200px;
}
#left{
position: absolute;
left: 0;
top: 0;
}
#right{
position: absolute;
right: 0;
top: 0;
}
</style>
</head>
<body>
<div id="header">header</div>
<div id="content">
<div id="middle">middle</div>
<div id="left">left</div>
<div id="right">right</div>
</div>
<div id="footer">footer</div>
</body>
</html>
flex法
核心:将父元素开启flex布局,默认flex-direction
为row
,即子元素从左到右排列。通过flex:1
给#middle
分配剩余空间,数字表示占剩余空间的多少份数,由于只给#middle
设置,所以其占据了剩余空间的全部
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>flex法</title>
<style>
*{
margin: 0;
padding: 0;
}
#header,#footer{
background-color: gray;
}
#content{
display: flex;
}
#middle{
background-color: skyblue;
flex: 1;
}
#left,#right{
background-color: pink;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div id="header">header</div>
<div id="content">
<div id="left">left</div>
<div id="middle">middle</div>
<div id="right">right</div>
</div>
<div id="footer">footer</div>
</body>
</html>