January 14, 2013

How do I set background color of text only in CSS?

Question by Hithere Paperbag

enter image description here

What I want is for the green background not to be 100% of the page width.
I want it just behind the text.
Html:

<!DOCTYPE html>

<head> 
<link rel="stylesheet" type="text/css" href="style.css">
</head> 

<body> 

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

</body> 

style.css:

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

Answer by BalusC

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.

Answer by Starx

A very simple trick to do so, is to add a <span> tag and add background color to that. It will look just the way you want it.

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

And CSS

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

WHY?

<span> tag in an inline element tag, so it will only span over the content faking the effect.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!