下面是几种方法的公用部分(右自适应也是一样的,换一下方向)
html:
<div class="demo"> <div class="sidebar">我是固定的</div> <div class="content">我是自适应的</div> </div>
css:
.sidebar,.content{ height: 300px; } .sidebar{ background-color: red;
width: 300px; } .content{ background-color: green; }
1. 左脱离文档流,右margin
1.1 左float
.demo .sidebar{float: left;}.demo .content{margin-left: 310px;}
1.2 左absolute
.sidebar{position: absolute;top: 0;left: 0;}.content{margin-left: 310px;}
2. flex布局(左定宽,右flex设置为1,自动伸展,此处注意flex兼容性,可以通postcss等后处理器自动加上前缀)
.demo{display: flex;}.sidebar{width: 300px;
margin-right:10px;}.content{flex: 1;}
效果图如下: