Let's say I have an img
element inside a div
, how do I make the div
have the same width and height of its content using CSS?
Using inline-block property: Use display: inline-block property to set a div size according to its content.
Answer: Use the CSS3 flexbox With CSS3 flex layout model you can very easily create the equal height columns or <div> elements that are aligned side by side. Just apply the display property with the value flex on the container element and the flex property with the value 1 on child elements.
Answer: Use the CSS max-width Property You can simply use the CSS max-width property to auto-resize a large image so that it can fit into a smaller width <div> container while maintaining its aspect ratio.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With