自適應佈局是一種很常見的佈局方式,現將常見的幾種實現方式列下:
1:利用float
左右兩div分別左右浮動,不再佔用文檔流,塊元素div.main自動佔據整行,然後給main添加左右margin分別爲左右兩塊元素的寬,代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.con{width: 500px;
height: 100px;
}
div{
height: 100px;
}
.left{
float: left;
width: 100px;
background: dodgerblue;
}
.right{
float: right;
width: 100px;
background: peru;
}
.main{
background: yellowgreen;
margin: 0 100px;
}
</style>
</head>
<body>
<div class="con">
<div class="left">left</div>
<div class="right">right</div>
<div class="main">main</div>
</div>
</body>
</html>
2、利用絕對定位(圖如上)
左右兩個div分別絕對定位到父元素左右,中間div.mian設置margin分別爲左右兩元素的寬
代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.con{width: 500px;
height: 100px;
position: relative;
}
div{
height: 100px;
}
.left{
position: absolute;
left: 0;
width: 100px;
background: dodgerblue;
}
.right{
position: absolute;
right: 0;
width: 100px;
background: peru;
}
.main{
background: yellowgreen;
margin: 0 100px;
}
</style>
</head>
<body>
<div class="con">
<div class="left">left</div>
<div class="right">right</div>
<div class="main">main</div>
</div>
</body>
</html>
3、利用負的margin
三元素分別浮動,中間元素width:100%
然後在利用負的margin給left和right定位,
最後給div.main的子元素設置左右margin分別爲左右倆元素的寬度
實現效果如圖一。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.con{width: 500px;
height: 100px;
}
div{
height: 100px;
}
.left{
float: left;
width: 100px;
background: dodgerblue;
margin-left: -100%;
}
.right{
float: left;
width: 100px;
background: peru;
margin-left: -100px;
}
.main{
width: 100%;
float: left;
background: yellowgreen;
}
.son{
margin:0 100px;
}
</style>
</head>
<body>
<div class="con">
<div class="main">
<div class="son">main</div>
</div>
<div class="left">left</div>
<div class="right">right</div>
</div>
</body>
</html>