1、浮动 + margin(正)
-
左侧固定,右侧自适应
将固定块左浮动,自适应块设置margin-left
html:
<div class="container">
<div class="fix">左侧固定</div>
<div class="content">右侧自适应</div>
</div>
css:
/* 浮动方式 + margin*/
.container {
background-color: #87ceeb;
}
.fix{
float: left;
width: 300px;
height: 400px;
background-color: #fa8072;
}
.content {
margin-left: 300px;
height: 400px;
background-color: #ffc0cb;
}
-
右侧固定,左侧自适应
html结构不变,将固定块右浮动,然后自适应块设置margin-right
/* 浮动方式 + margin 右侧固定*/
.fix {
float: right;
width: 300px;
height: 400px;
background-color: #fa8072;
}
.content {
margin-right: 300px;
height: 400px;
background-color: #ffc0cb;
}
2、浮动 + 负margin
参考: 负外边距 浮动情况下的负外边距
- margin-left 和 margin-top:影响自身元素,将向指定方向偏移。
- margin-right 和 margin-bottom:影响相邻元素,将其拖入指定方向
- 设置了position为absolute的元素,脱离文档流;如果设置了负的margin-left 或 margin-top,元素也会按照设定的方向移动相应的距离;如果设置了负的margin-right或margin-bottom,由于元素已经脱离文档流,则对后面的元素无影响。
- 浮动元素(float):当浮动方向与负值的margin方向一致时,元素会往对应的方向上移动对应的距离;当浮动方向与负值的margin方向相反时,则元素本身不动,元素之前或者之后的元素会向该元素的方向移动相应的距离。
html:
<div class="container">
<div class="auto">
<div class="content">自适应</div>
</div>
<div class="fix">固定</div>
</div>
css:
/* 负margin +float 左侧固定 右侧自适应 */
.auto {
float: right;
width: 100%;
margin-left: -300px;
}
.content{
margin-left: 300px;
height: 400px;
background-color: #ffc0cb;
}
.fix {
float: left;
width: 300px;
height: 400px;
background-color: #fa8072;
}
右侧固定,左侧自适应,只需将自适应元素浮动方向改为左侧,margin-left改为margin-right
/* 右侧固定 左侧自适应 */
.auto {
float: left;
width: 100%;
margin-right: -300px;
}
.content{
margin-right: 300px;
height: 400px;
background-color: #ffc0cb;
}
.fix {
float: left;
width: 300px;
height: 400px;
background-color: #fa8072;
}
3、绝对定位
html:
<!-- 绝对定位 -->
<div class="container">
<div class="content">自适应</div>
<div class="fix">固定</div>
</div>
css:
/* 绝对定位 右侧固定*/
.container{
position: relative;
}
.content{
position: absolute;
right: 300px;
left:0;
height: 400px;
background-color: #ffc0cb;
}
.fix{
position: absolute;
right: 0;
width: 300px;
height: 400px;
background-color: #fa8072;
}
4、flex布局
给父级设置display:flex , 让自适应区域flex:1,固定区域用width设置宽度
css:
.container {
display: flex;
}
.fix {
width: 300px;
height: 400px;
background-color: #fa8072;
}
.content {
flex: 1;
background-color: #ffc0cb;
}
html:
<div class="container">
<div class="content">自适应</div>
<div class="fix">固定</div>
</div>
5、table布局
可将父级设置为display: table,子元素设置为display:table-cell
html:
<div class="container">
<div class="content">自适应</div>
<div class="fix">固定</div>
</div>
css:
/* table布局 */
.container {
width: 100%;
display: table;
}
.content{
display: table-cell;
background-color: #ffc0cb;
}
.fix{
display: table-cell;
width: 300px;
height: 400px;
background-color: #fa8072;
}
6、网格(grid)布局
具体细节参看: http://www.css88.com/archives/8506
html:
<div class="container">
<div class="content">自适应</div>
<div class="fix">固定</div>
</div>
css:
.container {
display: grid;
grid-template-columns: auto 300px;
grid-template-rows: 400px;
}
.content{
background-color: #ffc0cb;
}
.fix{
background-color: #fa8072;
}