brad
brad

Reputation: 443

simple div containing span won't size correctly

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.

Upvotes: 16

Views: 13032

Answers (2)

timmfin
timmfin

Reputation: 2055

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.

Upvotes: 15

fuxia
fuxia

Reputation: 63606

Add overflow:auto to the div.

Upvotes: 4

Related Questions