您的位置:首页 > Web前端 > CSS

实现三个并排div,两边固定宽度,中间自适应的四个方法

2016-04-08 11:08 579 查看
个人整理的实现三个并排div,两边固定宽度,中间自适应的四个方法,废话不多说,先上代码,可以直接复制看效果。

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Description" content="">
<title>Document</title>
<style>
html,body{width:100%;height:100%;margin:0;padding:0;}
.cf:after{content:"";display:block;height:0;clear:both;}
.wrap{width:100%;height:200px;}
.left{width:400px;background:red;}
.center{background:#ececec;}
.right{width:400px;background:yellow;}
/*float法*/
.float .left{float:left;height:200px;}
.float .center{margin:0 400px;height:200px;}
.float .right{float:right;height:200px;}
/*position法*/
.position{position:relative;}
.position .left{position:absolute;top:0;left:0;height:200px;}
.position .center{height:200px;margin:0 400px;}
.position .right{position:absolute;top:0;right:0;height:200px;}
/*table法*/
.table{display:table}
.table .inner{display:table-cell;}
/*flex法*/
.flex {display:box;display:-webkit-box;display:-moz-box;display:-moz-box;}
.flex .left{height:200px;}
.flex .center{-webkit-box-flex:1;box-flex:1;-moz-box-flex:1;}
.flex .right{height:200px;}
</style>
</head>
<body>
<div class="wrap float cf">
<div class="left"></div>
<div class="right"></div>
<div class="center">
欢迎来到德莱联盟1!
</div>
</div><br/>
<div class="wrap position">
<div class="left"></div>
<div class="center">
欢迎来到德莱联盟2!
</div>
<div class="right"></div>
</div><br/>
<div class="wrap table">
<div class="inner left"></div>
<div class="inner center">
欢迎来到德莱联盟3!
</div>
<div class="inner right"></div>
</div><br/>
<div class="wrap flex">
<div class="left"></div>
<div class="center">
欢迎来到德莱联盟4!
</div>
<div class="right"></div>
</div><br/>
</body>
</html>


 float法

通过使两边的div左右浮动,脱离文档流,再为中间的div设置margin-left,margin-right值为左右div的宽度即可.此处应该注意的是中间div在代码中的位置,应该放在最后。存在问题:在屏幕宽度减少至一定程度后,右边div会错位,另起一行。

Postion法

其实跟float法异曲同工。存在问题:在屏幕宽度减少至一定程度后,右边div错位导致div之间会有重叠。

以上是网上常见的两种方法,下边是我个人扩展的两种方法,不知道是否存在bug.

Table法

超级简单,父元素设置display:table;width:100%,子元素设置display:table-cell即可。在屏幕宽度减少至一定程度后,div不会错位。不支持ie7以下浏览器,话说微软官方都宣布放弃了ie10的技术支持,ie的这点瑕疵可以忽略不计。

Display:box法

利用css3的弹性盒子模型设置父元素display:box;中间div设置box-flex:1。因为是新属性,注意添加前缀兼容不同浏览器,不支持万恶的IE。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  css 自适应 css3