宽度自适应布局

自适应布局是一种很常见的布局方式,现将常见的几种实现方式列下:

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>


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值