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