自适应布局是一种很常见的布局方式,现将常见的几种实现方式列下:
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>