Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple div containing span won't size correctly

Tags:

html

css

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.

like image 621
brad Avatar asked Apr 10 '10 16:04

brad


2 Answers

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.

like image 81
timmfin Avatar answered Oct 15 '22 03:10

timmfin


Add overflow:auto to the div.

like image 27
fuxia Avatar answered Oct 15 '22 03:10

fuxia