CSS布局——左右定宽,中间自适应
1、左边使用float: left,右边使用float: right,中间部分要放在后边
<div class="box">
<div class="left">left</div>
<div class="right">right</div>
<div class="middle">middle</div>
</div>
.left,.middle,.right{
height: 100vh;
}
.left{
float: left;
width: 200px;
background-color: red;
}
.middle{
background-color: green;
}
.right{
float: right;
width: 200px;
background-color: yellow;
}
2、flex布局
<div class="box">
<div class="left">left</div>
<div class="middle">middle</div>
<div class="right">right</div>
</div>
.left,.middle,.right{
height: 100vh;
}
.box{
display: flex;
}
.left{
width: 200px;
background-color: red;
}
.middle{
flex: 1;
background-color: green;
}
.right{
width: 200px;
background-color: yellow;
}
3、绝对定位
<div class="box">
<div class="left">left</div>
<div class="middle">middle</div>
<div class="right">right</div>
</div>
.left,.middle,.right{
height: 100vh;
}
.left{
width: 200px;
background-color: red;
position: absolute;
top: 0px;
left: 0px;
}
.middle{
background-color: green;
margin-left: 200px;
margin-right: 200px;
}
.right{
width: 200px;
background-color: yellow;
position: absolute;
top: 0;
right: 0;
}
4、圣杯布局(左右两边负边距,整体padding)
<div class="box">
<div class="middle">middle</div>
<div class="left">left</div>
<div class="right">right</div>
</div>
.box{
padding: 0 200px;
}
.left,.middle,.right{
height: 100vh;
float: left;
position: relative;
}
/* 负的margin-left会让元素沿文档流向左移动,如果负的数值比较大就会一直移动到上一行。 */
.left{
width: 200px;
background-color: red;
margin-left: -100%; /* 向左移动一整个行的宽度,由于left左边是父元素的边框,所以left继续跳到上一行左移,一直移动到上一行的开头,并覆盖了middle部分 */
left: -200px;
}
.middle{
width: 100%;
background-color: green;
}
.right{
width: 200px;
background-color: yellow;
margin-left: -200px; /* 向左移动父元素padding-right的宽度 */
right: -200px;
}
5、双飞翼布局
圣杯布局和双飞翼布局解决问题的方案在前一半是相同的,也就是三栏全部float浮动,左右两栏加上负margin让其跟中间栏div并排,以形成三栏布局。不同在于解决 “中间栏div内容不被遮挡”问题的思路不一样。
<div class="box">
<div class="middle">
<div class="content">middle</div>
</div>
<div class="left">left</div>
<div class="right">right</div>
</div>
.left,.middle,.right{
height: 33.33vh;
float: left;
}
.content{
margin: 0 200px;
}
.left{
width: 200px;
background-color: red;
margin-left: -100%;
}
.middle{
width: 100%;
background-color: green;
}
.right{
width: 200px;
background-color: yellow;
margin-left: -200px;
}
6、table实现
<table>
<tr>
<td class="left">left</td>
<td class="middle">middle</td>
<td class="right">right</td>
</tr>
</table>
table{
width: 100%;
height: 100vh;
border-collapse: collapse;
}
.left{
width: 200px;
background-color: red;
}
.middle{
background-color: green;
}
.right{
width: 200px;
background-color: yellow;
}