Make non-wrapping div expand when content overflows the page

依然范特西╮ 提交于 2019-12-10 12:07:00

问题


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).


回答1:


display: inline-block; to the rescue!

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



回答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/




回答3:


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.




回答4:


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/



来源:https://stackoverflow.com/questions/18199479/make-non-wrapping-div-expand-when-content-overflows-the-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!