How to make div the same width and height of the content?

Say I have an img element inside a div , how do I make a div have the same width and height of its content using CSS?

+6
html css
source share
5 answers

A floating div will make it compressed, and the div will only have room for the content inside.

You will probably need to use clear for the following elements.

Another way would be to use inline-block .

+11
source share

inline-block is right.

 <div style="border:1px solid red;display:inline-block"> <img src="http://www.google.com/intl/en_ALL/images/srpr/logo1w.png" alt="" style="border:1px solid green" /> </div> 
+4
source share

By default, the div will have the same height - unless you limit it in any way or add padding or margin. But the default width will fill the available space. If you want the width to be compressed to “compress” the content, you will either have to swim or make it an absolute position.

The problem with this (depending on your needs) is that both of them effectively take it out of the normal layout. If you need it to still be part of the regular layout, you will need to do something like this (borders are included so you can tell what is happening):

 <html> <head> <title>pdf test</title> <style type="text/css"> #a { position:relative; border: 1px solid green; } #b { float: left; border: 1px solid red; } </style> </head> <body> <div>Top</div> <div id="a"> <div id="b"> asdf<br/> typewriter</br> fdsa </div> <div style="clear:both;"></div> </div> <div> Bottom </div> </body> </html> 

Outer div #a works like a regular div. The important part here is that #a is position: relative . This creates a positioning context within which #b will float. This “double wrapped” approach will allow the div to still work in the layout as a “normal” div, allowing you to “sniff” the width / height from #b through Javascript if you need it.

So ... it depends on your needs, but it should lead you in the right direction.

Good luck

+4
source share

try this css:

 div { display: inline; } 
+2
source share

Inline-Block is not supported in IE for any default block level elements (e.g. div, h1-h ~, etc.).

The behavior of the built-in block is to automatically measure the width and height when resolving things such as position, margins, and indents. So you really need to use

 <span style="display: inline-block"> </span> 

and then you will have a browser compatible code :)

Enjoy.

+2
source share

All Articles