Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Width of float no longer shrinks to fit when contents wrap to multiple lines [closed]

Here is a test file.

Resize the window to be wide enough to hold all four boxes. Notice the container is no wider than the boxes, as intended.

Resize the window to be small enough that the boxes are on more than one line. Notice the container is the full width of the page (this is unintended).

Why? Is it possible to prevent this in a way that does not depend on the size of the boxes?

(Seen on Firefox 3.5 and Chrome 4.0.221.8. If a solution doesn't work in IE6, that's fine.)

like image 401
Chris Boyle Avatar asked Oct 14 '09 10:10

Chris Boyle


2 Answers

CSS 2.1 section 10.3.5 Floating, non-replaced elements (http://www.w3.org/TR/CSS21/visudet.html#float-width) says that:

width = min(max(preferred minimum width, available width), preferred width)

  • preferred minimum width = width of one of inner boxes, as they're all the same size.
  • available width = width of the page minus margins/borders.
  • preferred width = width of all inner boxes side-by-side.

This is completely sane for cases of text wrapping (imagine if the width changed depending on how close the line ends got to the edge of the available space) but not what you want here. I can't see a way to avoid this, though.

like image 88
James Ross Avatar answered Nov 19 '22 18:11

James Ross


I encountered this problem with a span of text that's wrapping because of a parent div's max-wdith. The border wasn't shrinking down on the right.

Here's a JS solution:

Remove the float on everything and make the photos inline, then move the background to a wrapper div and add a jquery one-liner to fix:

<script>$('#galleryWrapper').width($('.gallery').width());</script>

Here's the code:

http://jsbin.com/odeya3

like image 31
webXL Avatar answered Nov 19 '22 19:11

webXL