I thought I was pretty knowledgeable about CSS but this simple problem baffles me.
<div><span>sample text</span></div>
results in the div's height being smaller than the height of the span if the span has padding.
I realize that there are ways to use "float" to make the div size correctly, but floats always seem to introduce undesired side effects.
Isn't there a clean simple way to tell the div to size to fit its contents? Seems pretty basic to me. Maybe I'm missing something.
In the basic case, just use display: inline-block
on the span.
Here is my test case (works in FF, Chrome, and IE 6-8):
<!DOCTYPE HTML>
<html>
<head>
<title>Span padding test</title>
</head>
<body>
<div style="background-color: yellow; border: 1px solid red;">
<span style="padding: 50px; display: inline-block;">test</span>
</div>
</body>
</html>
The reason why adding float: left
to the div and span fixes this is because floating an inline element implicitly converts it to a block element. If you are unfamiliar with the nuances between divs and spans (aka the difference between block and inline elements), reading http://www.maxdesign.com.au/articles/inline/ should help.
There are a few other ways to solve this but it is hard to say which one is best without know more about the rest of the markup and styles.
Add overflow:auto
to the div.
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