How do I set a background-color for the width of text, not the width of the entire element, using CSS?

Hithere Paperbag picture Hithere Paperbag · Jan 14, 2013 · Viewed 450.1k times · Source

What I want is for the green background to be just behind the text, not to be 100% of the page width. Here is my current code:

Answer

BalusC picture BalusC · Jan 14, 2013

Put the text in an inline element, such as a <span>.

<h1><span>The Last Will and Testament of Eric Jones</span></h1>

And then apply the background color on the inline element.

h1 {
    text-align: center; 
}
h1 span { 
    background-color: green; 
}

An inline element is as big as its contents is, so that should do it for you.