float布局
- 注意浮动,需要将中间元素放置在同级左右元素后面;
- 清除浮动,可以通过在父元素中设置
overflow:hidden
清除元素浮动; - 不要忘记设置高度;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<style>
.wrap {
min-width: 800px;
height: 500px;
overflow: hidden;
}
.left{
width: 200px;
float: left;
height: inherit;
background-color: green;
}
.right {
width: 200px;
float: right;
height: inherit;
background-color: yellow;
}
.middle{
height: inherit;
background-color: red;
margin: 0 200px;
}
</style>
<body>
<div class="wrap">
<div class="left"></div>
<div class="right"></div>
<div class="middle"></div>
</div>
</body>
</html>
定位布局
- 父元素设置position定位(当然如果直接放在body元素下也可以);
- 设置子元素中左右子元素的
position:absolute
绝对定位,并分别放两边; - 中间元素的宽度会填满宽度,可以设置左右的
margin:0 200px
;
<style>
* {
padding: 0px;
margin: 0px;
}
.main {
min-width: 400px;
height: 500px;
display: relative;
}
.left {
position: absolute;
left: 0;
top: 0;
width: 200px;
height: inherit;
background-color: red;
}
.right {
position: absolute;
right: 0;
top: 0;
width: 200px;
height: inherit;
background-color: yellowgreen;
}
.middle {
height: inherit;
background-color: blue;
margin: 0 200px;
}
</style>
<div class="main">
<div class="left"></div>
<div class="middle"></div>
<div class="right"></div>
</div>
flex布局
- 弹性布局,需要在父元素中设置
display:flex
; - 在左元素和右元素中,设置元素的固定宽度;
- 中间元素需要设置
flex:1
,表示flex-grow:1,因为其他两个元素宽度固定,flex:1
表示充满剩余空间;
<style>
* {
padding: 0px;
margin: 0px;
}
.main {
min-width: 400px;
height: 500px;
display: flex;
}
.left {
width: 200px;
height: inherit;
background-color: red;
}
.right {
width: 200px;
height: inherit;
background-color: yellowgreen;
}
.middle {
height: inherit;
background-color: blue;
flex: 1;
}
</style>
</head>
<body>
<div class="main">
<div class="left"></div>
<div class="middle"></div>
<div class="right"></div>
</div>
</body>