css三种方式实现圣杯布局
圣杯布局是指两端固定宽度,中间宽度自适应的布局,常用于三栏形式的顶部布局,常用的三种实现圣杯布局的方式float方式,flex方式和position方式
一 、float方式实现
看了别人用float方式实现的圣杯布局发现会超出文档区域一个元素的宽度,这里采用calc的方式,将中间区域设置为100%减掉左边栏加右边栏的宽度
<!DOCTYPE html>
<html>
<head>
<style>
*{
margin: 0;
padding: 0;
}
.main{
width: 100vw;
height: 300px;
}
.main>div{
float: left;
}
.middle{
background: maroon;
height: 100%;
margin-left: 100px;
margin-right: 100px;
width: calc(100% - 200px);
}
.left{
width: 100px;
height: 100%;
margin-right:-100px;
background: rgb(206, 166, 58);
}
.right{
width: 100px;
height: 100%;
margin-left: -100px;
background: lime;
}
</style>
</head>
<body>
<div class="main">
<div class="left">left</div>
<div class="middle">middle</div>
<div class="right">right</div>
</div>
</body>
<script>
</script>
</html>
二、flex方式实现
flex内部元素默认会横向排列,flex属性为flex-grow,flex-shrink和flex-basis的简写形式,其中flex-grow设置项目放大等级,1为自动填充剩余区域,flex-shrink设置项目的缩小等级,flex-basis定义项目所占主轴空间建议,阮一峰网络日志flex篇直达
<!DOCTYPE html>
<html>
<head>
<style>
*{
margin: 0;
padding: 0;
}
.container{
min-width: 300px;
min-height: 500px;
height: 100vh;
display: flex;
flex-direction: column;
}
.header{
flex: 0 1 100px;
background: royalblue;
}
.footer{
flex: 0 1 100px;
background: salmon;
}
.main{
flex: 1 1;
display: flex;
}
.left{
background: paleturquoise;
flex:0 1 200px
}
.middle{
background: peru;
flex: 1 1;
}
.right{
background:purple;
flex: 0 1 200px
}
</style>
</head>
<body>
<div class="container">
<div class="header"></div>
<div class="main">
<div class="left"></div>
<div class="middle"></div>
<div class="right"></div>
</div>
<div class="footer"></div>
</div>
</body>
<script>
</script>
</html>
三、position方式实现
<!DOCTYPE html>
<html>
<head>
<style>
*{
margin: 0;
padding: 0;
}
body{
height: calc(100vh - 200px);
padding: 100px 0 100px 0;
}
.header{
margin: -100px 0 0 0;
height: 100px;
background: salmon;
}
.footer{
margin: 0 0 -100px 0;
height: 100px;
background: sienna;
}
.main{
height: 100%;
position: relative;
padding: 0 100px 0 100px;
}
.left{
background: paleturquoise;
position: absolute;
width: 100px;
height: 100%;
left: 0;
top: 0;
}
.middle{
background: peru;
width: 100%;
height: 100%;
}
.right{
background:purple;
position: absolute;
height: 100%;
width: 100px;
right: 0;
top: 0;
}
</style>
</head>
<body>
<div class="header"></div>
<div class="main">
<div class="left"></div>
<div class="middle"></div>
<div class="right"></div>
</div>
<div class="footer"></div>
</body>
<script>
</script>
</html>