前言
两边固定中间自适应这种布局方式在平常的项目中非常常见,本文介绍三种基础方法,根据这三种方法也可以组合出不同的方法。
利用 flex布局实现
在这里插入代码片<style>
html,
body,
.box {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
}
.box {
display: flex;
}
.mid {
flex: 1;
height: 100%;
background-color: #ff0;
}
.right {
flex: 0 0 200px;
height: 100%;
background: #f0f;
}
.left {
flex: 0 0 200px;
height: 100%;
background: #f00;
}
</style>
</head>
<body>
<div class="box">
<div class="right">right</div>
<div class="mid">mid</div>
<div class="left">left</div>
</div>
</body>`在这里插入代码片`
这里的flex:1等同于
flex-grow: 1; //放大的比例。默认为0,如果为1则是放大,如果为2则是放大11的两倍。以此类推
flex-shrink: 1;//随小比例,空间不足是则会缩下,0是不会,1是会
lex-basis: 0%;项目自身的大小,默认为auto,可设置为固定值
利用定位
在这里插<style>
html,
body,
.box {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
}
.box {
position: relative;
}
.mid {
position: absolute;
left: 200px;
right: 200px;
height: 100%;
background-color: #ff0;
}
.right {
position: absolute;
right: 0;
width: 200px;
height: 100%;
background: #f0f;
}
.left {
position: absolute;
left: 0;
width: 200px;
height: 100%;
background: #f00;
}
通过定位的方式来实现此布局,这里就不再赘述
float方式
在这里插入代码片<style>
html,
body,
.box {
padding: 0;
margin: 0;
height: 100%;
}
.box {
padding: 0 200px;
}
.mid {
float: left;
width: 100%;
height: 100%;
background-color: #ff0;
}
.right {
margin-right: -200px;
float: right;
width: 200px;
height: 100%;
background: #f0f;
}
.left {
float: left;
margin-left: -200px;
width: 200px;
height: 100%;
background: #f00;
}
</style>
这里有一点需要注意的是不能将父盒子设置宽度为100%,父级的盒子由子盒子撑起来。
总结
这三种方式是作为三栏布局的常用方式,由这三种方式可变化出不同的方式,在这里就不多演示,大家有兴趣可以尝试。