- 使用绝对定位
左右使用绝对定位 由于绝对定位脱离标准流 center会自动在左右的下面 使用margin 留出左右元素的宽度 这样可以使中间自适应了
div 元素
<div class="boxleft">left</div>
<div class="boxcenter">content</div>
<div class="boxright">right</div>
css 样式
/*考虑到浏览器兼容性 最好还是加上这句*/
html,body{ margin: 0px; padding:0; }
.boxleft, .boxright {
position: absolute;
top:0;
width: 200px;
background-color:blue;
}
.boxleft {
left:0;
}
.boxright {
right: 0;
}
.boxcenter {
margin: 0 200px;
background-color: pink;
}
- 使用浮动定位
左右浮动 左右脱离标准流 center 在正常的文档流中 使用margin指定左右边距
<div class="boxleft">left</div>
<div class="boxright">right</div>
<div class="boxcenter">content</div>
.boxleft {
float: left;
width: 200px;
background-color:blue;
}
.boxright {
float:right;
width: 200px;
background-color:blue;
}
.boxcenter {
margin: 0 200px;
}
该布局法的好处是受外界影响小,但是不足是 三个元素的顺序,center一定要放在最后,这是和绝对定位不一样的地方,center占据文档流位置,所以一定要放在最后,左右两个元素位置没有关系。当浏览器窗口很小的时候,右边元素会被挤到下一行
- 使用flex布局
在外围包裹一层div,设置为display:flex;两侧设为固定的不缩放 宽度中间设置flex:1 。
flex 0 0 200px;可能几个属性会问到 分别是 flex-grow放大比例, flex-shrink缩小比例 和 flex-basis项目将占据固定空间的简写
<div class="wrapper">
<div class="boxleft">left</div>
<div class="boxcenter">content</div>
<div class="boxright">right</div>
</div>
.wrapper {
display: flex;
}
.boxleft, .boxright {
flex: 0 0 200px;
background-color:blue;
}
.boxcenter {
flex: 1;
background-color: pink;
}