天天看點

寬度自适應布局

自适應布局是一種很常見的布局方式,現将常見的幾種實作方式列下:

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>