raldi raldi - 11 months ago 45
HTML Question

How do I keep a DIV from expanding to take up all available width?

In the following HTML, I'd like the frame around the image to be snug -- not to stretch out and take up all the available width in the parent container. I know there are a couple of ways to do this (including horrible things like manually setting its width to a particular number of pixels), but what is the right way?

Edit: One answer suggests I turn off "display:block" -- but this causes the rendering to look malformed in every browser I've tested it in. Is there a way to get a nice-looking rendering with "display:block" off?

Edit: If I add "float: left" to the pictureframe and "clear:both" to the P tag, it looks great. But I don't always want these frames floated to the left. Is there a more direct way to accomplish whatever "float" is doing?

.pictureframe {
display: block;
margin: 5px;
padding: 5px;
border: solid brown 2px;
background-color: #ffeecc;
#foo {
border: solid blue 2px;
float: left;
img {
display: block;

<div id="foo">
<span class="pictureframe">
<img alt=''
src="http://stackoverflow.com/favicon.ico" />
Why is the beige rectangle so wide?

Jim Jim
Answer Source

The right way is to use:

.pictureframe {
    display: inline-block;

However, Firefox 2.x doesn't support this, so you may need to use a workaround, such as using display: table instead for that browser:

.pictureframe {
    display: table;
    display: inline-block;

Setting it to be a table has some drawbacks, depending on your situation, table-cell may be more appropriate.

Edit: Floating the element also produces the same effect, this is because floating elements use the same shrink-to-fit algorithm for determining the width.