I would appreciate pointers to documentation or explanation to help me understand the difference between display values "block" and "inline-block". In particular, I do not understand why the minimum width of a div with display: inline-block; is the width of it's widest content but with display: block; the div can be narrower than its content, with the content overflowing horizontally.
w3.org description of display says display: block; causes an element to generate a block-box and for display: inline-block; that the inside of an inline-block is formatted as a block-box. This is why I thought the relationship with the contents would be the same either way. But it is not.
Consider the following:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/lose.dtd"> <html> <head> <title>test</title> </head> <body> <div style="display: block; background-color: red;"> <p>before</p> <div style="width: 300px; background-color: green;"> <p>test</p> </div> <p>after</p> </div> </body> </html>
This renders the same in Firefox, Chrome and IE: the width of the outer div is the width of the viewport, which may be wider or narrower than the width of the inner div. If the browser window is made sufficiently narrow, the inner div does not fit - horizontal scrollbar appears and when one scrolls right one sees that the red background is only as wide as the viewport while the green background overflows to the right.
If the display of the outer div is changed from block to inline-block then the behaviour is quite different. If the viewport is wider than 300px then the width of the outer div is only 300px (i.e. just enough to contain the inner div). I understand this - no problem here. But, if the viewport is narrowed to less than 300px a horizontal scrollbar appears but this time when one scrolls to the right one sees that the red background (the outer div) width remains 300px. In this case, the inner div does not overflow the outer div and the outer div does not shrink horizontally to be narrower than the inner div.
If a "block-box" is created in both cases, why doesn't this block box contain all it's content in the same way, or overflow in the same way in both cases: why the difference?
I have tried to read the w3.org pages on box model and visual formatting but I don't see an explanation for this difference in "block-box" behaviour.
If the display type is block, is there some other attribute that can be set so that the inner div does not overflow (i.e. to make it the same as the inline-block type in this respect)?
I could just use inline-block and stop worrying, as this does what I want (i.e. contains the contents), but I don't like not understanding.