Let's say I have an img
element inside a div
, how do I make the div
have the same width and height o开发者_StackOverflow社区f its content using CSS?
Floating the div would make it shrinkwrap and so the div would only have room for the content inside.
You will probably need to use clear
on the elements coming afterwards.
Another way would be to use inline-block
.
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>
By default, the div will have the same height -- unless you restrict it somehow, or add padding or margin. But the default width will fill the available space. If you want the width to collapse down to "shrink-wrap" the content, you'll either have to float it, or make it absolute positioned.
The problem with this (depending on your needs) is that both of those effectively take it out of the normal layout. If you need it to still be part of the normal layout, you'll have to do something like this (the borders are included so you can tell what's going on):
<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>
The outer div #a
works like a normal div. The important part here is that #a
is position: relative
. That sets up a positioning context, within which #b
will float. This "double-wrapped" approach will let the div still work within the layout like a "normal" div, while allowing you to "sniff" the width/height from #b
via Javascript, if you need it.
So... it depends on what your needs are -- but this should set you in the right direction.
good luck!
try this css:
div {
display: inline;
}
Inline-Block is not supported in IE for any default block level elements (like div, h1-h~ etc).
Inline block behaviour is to auto size the width and the height while allowing things like position, margins and padding. So all you really need to do is use
<span style="display: inline-block">
</span>
and then you will have some browser compatible code :)
Enjoy.
精彩评论