7

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.)

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Chris Boyle
  • 11,423
  • 7
  • 48
  • 63
  • Maybe you could re-post the "test file" again. At the moment this question is rendered pretty useless without it. – Kev Jul 11 '12 at 23:25
  • @Kev I can't see why this question is closed. The test file was posted, is working now, and the question is useful. – mahemoff Sep 19 '12 at 23:40

2 Answers2

5

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.

James Ross
  • 66
  • 1
1

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

webXL
  • 1,630
  • 1
  • 15
  • 21
  • rather [do](http://stackoverflow.com/a/33511762/274502) something *like* `$('#id container').each(function(){ $(this).parent().width($(this).width()); });` as to keep every single item with their respective child width. – cregox Nov 04 '15 at 00:39