2

I have an unordered list and each list element contains a photo and a headline. My CSS sets up the grid to be a grid, where each row contains three photos. Sometimes the headline (or photo caption) is longer than the width of the photo and has to span two lines. In some situations, when the text spans 2+ lines, the list element below it gets pushed to the right and there is a big gap in the list. The only fix that works for me is adding the following HTML <div style="clear:both"></div> after every three <li></li> elements. The issue can be seen in the third row of the list elements. I've tried researching this issue, but have not found a CSS only method. In my example code, I applied the CSS clearfix class, but it doesn't seem to have any effect.

I'm using the latest version of Google Chrome.

Here is my code: http://jsfiddle.net/NVveP/1/

musubi
  • 1,256
  • 3
  • 14
  • 22
  • Is this good? http://jsfiddle.net/thirtydot/NVveP/2/. I'll write an actual answer tomorrow, if required. – thirtydot Jun 20 '12 at 00:36
  • Yes that works perfectly. Thank you! This unordered list is contained inside a div. In my original layout, the div was floated left, so the list also had to be floated left. Since then, I decided to change my layout to a non-floating div, so that's why removing the "float: left" css property solves my problem. If I kept my original layout and the list needed to be floated, what would be the solution for that? – musubi Jun 20 '12 at 00:55
  • "In my original layout, the div was floated left, so the list also had to be floated left." - the list didn't need to be floated. A floated element (such the outer `div`) will contain other floated elements. If you then changed your outer `div` to not be floated, you would then have to contain the floats in some other way, such as adding the `clearfix` class to the outer `div`. – thirtydot Jun 20 '12 at 09:19

1 Answers1

4

Having both float: left and display: inline-block will in effect nullify display: inline-block, because float: left forces display: block.

Hence, removing float: left allows display: inline-block to work, which combined with vertical-align: top is how you can achieve your desired layout.

See: http://jsfiddle.net/thirtydot/NVveP/3/

I also added a hack to make display: inline-block work in IE7, if that matters.

It would be more difficult to do this with floats. You'd need something to the effect of:

li:nth-child(3n+1) {
    clear: both;
}

Which has the problem of not working in older browsers such as IE7/8. Fortunately, there's no need to worry about this because display: inline-block is the solution here, not floats.

Community
  • 1
  • 1
thirtydot
  • 224,678
  • 48
  • 389
  • 349