How can I make my background-color fill all my content, even with horizontal scrolling?

拥有回忆 提交于 2020-07-19 07:27:47

问题


I'm using an <ol> to show a code snippet with line numbers. Since I'm showing program code, I disable wrapping (and enable indentation) by setting white-space: pre on li, which means an li's content can extend past the right margin and cause the page to have a horizontal scroll bar. So far so good.

The problem comes when I want to set background colors on some of the lis to call out particular lines of code. I can set background-color on the li, but the color only extends to the right margin of the page; in fact, the last 10 pixels or so of text (an amount equal to the body's right margin) has no background color. And if I scroll horizontally, it's even worse: the background color scrolls left off the page. The background-color is only one browser-width wide (minus the page margins).

Here's a fiddle illustrating the problem. If you scroll right, I want the background to be blue for as far as there's text.

How can I get the background-color to fill the full width of the content, even if the page scrolls horizontally?


回答1:


You can "shrink-wrap" each li's content with a combination of float and clear, as in this answer.

li {
    white-space: pre;
    background: blue;
    float:left;
    clear:left;
    min-width:100%;
}

The last line is from koala_dev's answer. It forces shorter-content elements to have full-width background.

Fiddle




回答2:


You can use display: inline-block to make each list item fit its content. Combine this with min-width:100%; to make shorter-content lis stretch to full container's width.

li {
    white-space: pre;
    background: blue;
    display: inline-block;
    min-width:100%;
}

Demo fiddle




回答3:


This is not possible with using directly a li item.

But a simple span inside the li fixes this.

Here is the relevant code:

span {
    white-space: pre; 
}
.highlight {
    background: blue;
}

Your markup would be along the lines of:

<ol>
    <li><span> Code Here... </span></li>
    <li><span class="highlight"> Code Here... </span></li>
</ol>

The reason for this is. If you change the li's display to anything else than list-item it will lose it's numbering. (In Chrome at least.) So this way you get both with just a bit more overhead.

A jsfiddle showcasing it: http://jsfiddle.net/tp6Um/4/




回答4:


I found a way to kind of fix your problem

li 
{
white-space:pre;
display:block;
width:150%;
}

set the percentage accordingly



来源:https://stackoverflow.com/questions/20776526/how-can-i-make-my-background-color-fill-all-my-content-even-with-horizontal-scr

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