tags:

views:

73

answers:

2

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.

+1  A: 

Add overflow:auto to the div.

toscho
This is the best way. It may create scroll bars if you're not careful, though.
tloflin
+1  A: 

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.

timmfin
note that display: inline-block does not work in IE6. Overflow: auto on the parent div would solve the problem to and even work in IE6
meo