Question

When a div has white-space: pre and has too much content, it will overflow the page, adding a scrollbar. How do I get the div to be as wide as it expands to?

Example: http://jsfiddle.net/TkcTZ/1/

If you scroll to the right, you'll see that the background only extends to the right of the viewport, not past the edge behind the overflowing text. If you inspect the div with web tools, you will see that it is because the div is only as wide as the background.

How do I make divs expand widthwise when their content overflows? I would like a CSS/HTML only solution (no javascript).

Was it helpful?

Solution 2

I seem to have fixed it by setting display: table and width: 100% on the containing div, like so: http://jsfiddle.net/TkcTZ/3/

OTHER TIPS

display: inline-block; to the rescue!

div {
    white-space: pre;
    background-color: red;
    display: inline-block;
}

The following updated fiddle should work for you:

http://jsfiddle.net/TkcTZ/2/

I have update the code with overflow:auto; This makes sure that div covers all its content with its background.

You can use overflow: auto to make the div scrollable so that the background color takes the 100% of the div width.

div {
    white-space: pre;
    background-color: red;
    overflow: auto;
}

Check this http://jsfiddle.net/nkHGZ/

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