简体   繁体   中英

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

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 li s 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?

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

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

Demo fiddle

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

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/

I found a way to kind of fix your problem

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

set the percentage accordingly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM