首页 > CSS浮动问题?

CSS浮动问题?

如何实现上图这样的效果?
外边的宽高固定,.container{width:1020px; position: relative; margin:64px 90px 0px;}
4张图片都采用浮动效果,img{float: left; display: block; margin:0 2px 4px;},但是最后一张无法到相应的位置,而出现了这样的情况,
请问该如何解决?
另外,为什么都float:left不成功呢?


在container里加个overflow:hidden;


第四块排在了第二块下边的右边说明了一切,原因应该是第二列那块宽度宽了,把第四张图挤下来了。你可以用chrome看下各块的盒子模型,一看便知。


你应该把最后一张图片设为float: none;看看。

没人说为什么都设为float:left不行,其实查查w3c的规范就知道了
http://www.w3.org/TR/CSS21/visuren.html#float-position

Here are the precise rules that govern the behavior of floats:
...
5 The outer top of a floating box may not be higher than the outer top of any block or floated box generated by an element earlier in the source document.

粗略的翻译就是:
float元素的outer top(上沿包括margin)不能高于之前块级和浮动元素。


如果都是float: left;的话,那么你这个结构多少还是有点问题的,浮动了之后,后一个元素会跟着前一个元素的位置走,所以第四个会在第三个旁边。

不过这个时候你可以设置一个margin-top: -150px;这样的值来把第四个拉上去,但是这样的话,前提要求知道前面几个元素的高度。

也或者可以考虑通过绝对定位的方式把第四个定位在最后的位置,在外围容器.container中设置padding-right留出空间给第四个元素。

再或者可以试一下下面这样的代码,随手在chrome里做的测试是OK,其他浏览器没测试过。

html<div class="wrap">
  <div class="box1"></div>
  <div class="box2"></div>
  <div class="box3"></div>
  <div class="box4"></div>
</div>
css.wrap {width:1020px; position: relative; height: 500px; border: 1px solid #f00;}
.wrap div {float: left;width: 250px;height: 400px;margin:10px 2px 4px;background-color: rgba(255,0,0,.5);}

.wrap .box2,
.wrap .box4 {width: 500px;height: 188px;}

.wrap .box3 {float: right;}

可以把左中右分成三部分,中间部分再分成两部分,计算好宽度


http://nec.netease.com/library/101121
看看这个布局吧,左右定宽,中间自适应。CSS的布局是很深奥的。

【热门文章】
【热门文章】