css 圣杯布局三种方式
所谓的圣杯布局就是左右两边大小固定不变,中间宽度自适应。我们可以用浮动、定位以及flex这三种方式来实现
一般这种布局方式适用于各种移动端顶部搜索部分,这是最常见的,如京东手机版主页面顶部搜索:

可以看到左边有个菜单按钮,中间是搜索框,右边是登录两个文字,左右大小是固定的,而中间部分则是随着手机屏幕尺寸的大小而自适应。
第一种方法 float实现:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 6 <title>Document</title> 7 <style type="text/css"> 8 *{ 9 margin: 0; 10 padding: 0; 11 color: black; 12 font-size: 45px 13 } 14 .main>div{ 15 float: left; 16 } 17 .main{ 18 width: 100%; 19 background: yellow 20 } 21 .center{ 22 background: red; 23 margin-left: 200px; 24 margin-right: -200px; 25 width: 100% 26 } 27 .left{ 28 background: pink ; 29 width: 200px; 30 margin-left: -100% 31 } 32 .right{ 33 background: blue ; 34 width: 200px; 35 margin-right: -200px 36 } 37 </style> 38 </head> 39 <body> 40 <div class="main"> 41 <div class="center">中间</div> 42 <div class="left">左边</div> 43 <div class="right">右边</div> 44 </div> 45 46 </body> 47 </html>
第二种 position实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
color: black;
font-size: 45px
}
.main div{
box-sizing: border-box;
}
.main{
width: 100%;
background: red;
position: relative;
padding-left: 200px;
padding-right: 200px;
}
.center{
width: 100%;
background: pink
}
.left{
background: yellow ;
width: 200px;
position: absolute;
left: 0;
top: 0;
}
.right{
background: blue ;
width: 200px;
position: absolute;
top: 0;
right:0
}
</style>
</head>
<body>
<div class="main">
<div class="center">z中间</div>
<div class="left">左</div>
<div class="right">右</div>
</div>
</body>
</html>
第三种 flex实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin:0;padding:0;
}
.container{
display: flex;
height: 100vh;
flex-direction: column;
}
header{
background: #000;
}
section{
flex:1;
background: pink;
display: flex;
}
footer{
background: #000;
}
.left{
background: red;
flex:0 0 100px;
}
.center{
flex:1;
background: blue;
}
.right{
flex:0 0 100px;
background: red;
}
</style>
</head>
<body>
<div class='container'>
<header>头部</header>
<section>
<div class='left'>左</div>
<div class='center'>中</div>
<div class='right'>右</div>
</section>
<footer>底部</footer>
</div>
</body>
</html>

浙公网安备 33010602011771号