开发者

Clearing last floated element in each row

I have a set of divs with variable heights that have been floated left. When there are too many of said divs on a single line, the next div wraps to a new row (as it should). The problem I'm having is that the new row is started at an offset x position on the new row, such that the div is beneath the last div in the previous row that has no taller divs behind it- quite often leaving a large margin on the left side.

div.entry 
{
    float: left;
    width: 180px;
    padding: 10px;
}

I essentially want it so that the last div.entry in each "row" (the one before it wraps to a new row) clears the float, so that the next row of floated divs are all aligned to the same height, and don't have a rather large gap on the left side. Illustrated in ASCII:

What I expect to happen:

+-----+ +-----+ +-----+ +-----+
|  A  | |  B  | |  C  | |  D  |
|     | |     | |     | +-----+
+-----+ |     | +-----+
        +-----+
+-----+ +-----+ +-----+ +-----+
|  E  | |  F  | |  G  | |  H  |
|     | |     | |     | +-----+
+-----+ |     | +-----+
        +-----+

What actually happens:

+-----+ +-----+ +-----+ +-----+
|开发者_开发知识库  A  | |  B  | |  C  | |  D  |
|     | |     | |     | +-----+
+-----+ |     | +-----+
        +-----+ +-----+ +-----+
                |  E  | |  F  |
                |     | |     |
                +-----+ |     |
                        +-----+
+-----+ +-----+
|  G  | |  H  |
|     | +-----+
+-----+

Michael


If float: left isn't mandatory, there's always display: inline-block which would be more suited for the job. Since the "inline flow" already works like you want.

.item {
    display: inline-block;
    vertical-align: top;
    width: 300px;
}

This pretty much behaves right in current browsers. See fiddle.

If you want compatibility with older browsers, there is a nice article on the mozilla blog describing the situation: http://blog.mozilla.org/webdev/2009/02/20/cross-browser-inline-block/


I had this problem once, I think I got around it my setting a min-height property to the divs.

Which gave me:

+-----+ +-----+ +-----+ +-----+
|  A  | |  B  | |  C  | |  D  |
|     | |     | |     | +-----+
+-----+ |     | +-----+
        +-----+ 
+-----+ +-----+ +-----+ +-----+ 
|  E  | |  F  | |  G  | |  H  |
|     | |     | |     | +-----+
+-----+ |     | +-----+
        +-----+ 


Other solution (not completly cross-browser) is to add

.item:nth-child(4n+1) { clear: left; }

Check this http://jsfiddle.net/AfUL3/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜