如何实现多个div水平均匀排列且量两端贴壁

下面先看一段代码实例:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.51texiao.cn/" />
<title>蚂蚁部落</title>
<style type="text/css">
.parent{
  width:480px;
  height:100px;
  border:1px solid red;
  overflow:hidden;
}
.parent div{
  width:100px;
  height:100px;
  background-color:green;
  margin-left:20px;
  float:left;
}
</style>
</head>
<body>
<div class="parent">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
</body>

</html>

以上代码虽然均匀分布了,但是左侧由于外边距的原因,不能够贴到父元素的内壁,不能够满足我们的效果,代码修改如下:
 <!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.51texiao.cn/" />
<title>蚂蚁部落</title>
<style type="text/css">
.parent{
  width:460px;
  height:100px;
  border:1px solid red;
  overflow:hidden;
}
.wrap{
  width:480px;
  height:100px;
  overflow:hidden
}
.parent .wrap div{
  width:100px;
  height:100px;
  background-color:green;
  margin-right:20px;
  float:right;
}
</style>
</head>
<body>
<div class="parent">
<div class="wrap">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
</div>
</body>
</html>

以上代码实现了想要的效果。方法就是在水平排列的div的外层再嵌套一个div,并将此div的宽度设置为480px,这样不会导致水平排列的div出现 换行。最外层的div设置宽度为460,并且将overflow属性值设置为hidden,这样就可以将右侧的margin-right区域给隐藏掉,于 是实现了我们想要的效果。
 

posted on 2015-12-31 09:53  土dou  阅读(938)  评论(0编辑  收藏  举报