Question

I've got a really frustrating problem with a web application I work on (I didn't originally write it). It uses frames for the layout scarily enough. The problem I'm having is that all elements with a background colour and border set via CSS default to 100% width. I've just tested div elements, paragraph elements etc.

I removed the stylesheet completely and then tested it and I had the same problem, so it's not the stylesheet causing the problem.

I wrote a quick test to make sure it wasn't conflicting code and used the same doctype and xmlns as ours - I get the same problem. Here's the example code.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
    #test {
        border:1px solid #ccc;
        background-color:#ddd;
    }
</style>
</head>
<body>
    <div id="test">
        Test information!
    </div>
</body>
</html>

Any ideas?

Was it helpful?

Solution

I think this is required by HTML/CSS. Block elements extend the full width unless there is something to stop them.

(FF has the same behaviour.)

OTHER TIPS

It's not because the element has a background or a border that it expands to the full with of the parent, it's because it's a block element. The background or border just makes you see how large the element really is.

The default width is actually not "100%", but "auto". The practical difference is that the element including borders uses 100% of the width, instead of the width excluding the borders becoming 100% of the width (making the width including borders wider than it's parent).

If you don't want the element to use the available width you can make it a floating element. Then it will adjust itself to it's content.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Test</title>
    <style type="text/css">
    #test1 {
        float: left;
        border:1px solid #ccc;
        background-color: #ddd;
    }
    #test2 {
        float: left;
        clear: both;
        border:1px solid #000;
        background-color: #ccf;
    }
    </style>
</head>
<body>
    <div id="test1">
        Test information!
    </div>
    <div id="test2">
        Test information!
    </div>
</body>
</html>

As Richard and BeefTurkey say, divs are block elements and will fill the width of the browser.

You can either use an inline element, such as a span

<span id="test">
    Test information!
</span>

or add some style to your div to force it to be inline

div#test { display: inline; }

Don't divs default to 100% (of parents size) because they're blocks? You could always try changing display to inline: #test {display:inline;}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top