一、两栏布局,右侧自适应?
方法一:
1.float左浮动
2.右模块margin-left撑出内容块做展示
3.为父级添加BFC,防止下方元素飞到上方
<div class="wrap">
<div class="left">左边</div>
<div class="right">右边</div>
</div>
<style>
.wrap{
/* 添加BFC */
overflow: hidden;
}
.left{
float: left;
width: 200px;
height: 400px;
background-color: coral;
}
.right{
margin-left: 200px;
height: 200px;
background-color: red;
}
</style>
方法二:flex布局
<div class="box">
<div class="left">左边</div>
<div class="right">右边</div>
</div>
<style>
.box{
display: flex;
}
.left{
width: 100px;
}
.right{
flex: 1;
}
</style>
二、三栏布局,中间自适应?
1.两边使用 float,中间使用 margin
<div class="wrap">
<div class="left">左侧</div>
<div class="right">右侧</div>
<div class="middle">中间</div>
</div>
<style>
.wrap {
background: #eee;
overflow: hidden; <!-- 生成BFC,计算高度时考虑浮动的元素 -->
padding: 20px;
height: 200px;
}
.left {
float: left;
width: 200px;
height: 200px;
background: coral;
}
.right {
float: right;
width: 120px;
height: 200px;
background: lightblue;
}
.middle {
margin-left: 220px;
height: 200px;
background: lightpink;
margin-right: 140px;
}
</style>
2.两边使用 absolute,中间使用 margin
<div class="container">
<div class="left">左边固定宽度</div>
<div class="right">右边固定宽度</div>
<div class="main">中间自适应</div>
</div>
<style>
.container {
position: relative;
}
.left,
.right,
.main {
height: 200px;
line-height: 200px;
text-align: center;
}
.left {
position: absolute;
top: 0;
left: 0;
width: 100px;
background: green;
}
.right {
position: absolute;
top: 0;
right: 0;
width: 100px;
background: green;
}
.main {
margin: 0 110px;
background: black;
color: white;
}
</style>
3.两边使用 float 和负 margin
<div class="main-wrapper">
<div class="main">中间自适应</div>
</div>
<div class="left">左边固定宽度</div>
<div class="right">右边固定宽度</div>
<style>
.left,
.right,
.main {
height: 200px;
line-height: 200px;
text-align: center;
}
.main-wrapper {
float: left;
width: 100%;
}
.main {
margin: 0 110px;
background: black;
color: white;
}
.left,
.right {
float: left;
width: 100px;
margin-left: -100%;
background: green;
}
.right {
margin-left: -100px; /* 同自身宽度 */
}
</style>
4.flex实现(推荐)
<div class="wrap">
<div class="left">左边</div>
<div class="middle">中间</div>
<div class="right">右边</div>
</div>
<style>
.wrap{
display: flex;
justify-content: space-between;
}
.left,.middle,.right{
height: 100px;
}
.left{
width: 100px;
background-color: coral;
}
.middle{
flex: 1;
background-color: green;
}
.right{
width: 120px;
background-color: red;
}
</style>