Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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" />    </span>    <p>      Why is the beige rectangle so wide?    </p>  </div>
like image 226
raldi Avatar asked Sep 24 '08 20:09

raldi


People also ask

How do I stop DIVS from expanding?

You should use display: table; It will shrink to the size of it's contents and can also be centered and positioning without having to assign a given width.

How do you make an element occupy full width?

If you set the width to 100% on the body element you will have a full page width. This is essentially equivalent to not setting a width value and allowing the default. If you want to use the body element as a smaller container and let the HTML element fill the page, you could set a max-width value on the body.

How do I make a div take the width of its content?

Using inline-block property: Use display: inline-block property to set a div size according to its content.


1 Answers

The right way is to use:

.pictureframe {     display: inline-block; } 

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.

like image 137
Jim Avatar answered Sep 29 '22 22:09

Jim