CSS: Add Background color only behind text and not entire section

Viewed 834

I have a text of 2 lines like the following:

This is a line
<br>
This is another line

And I need to add background color only behind the text

like this.

But only in the back of the letters, not the entire section.

How can I achieve that?

3 Answers

The text should be within <p> or <h1> or something similar. You can add style attributes to that elements (directly or with a separate .css file). In your case, you need "background-color":

<p style="background-color: red;"> Your text here </p>

Here is a link for more info on text & color.

Putting the element into the span will fix this issue. Try this:

<span style="background-color: black;">
This is a line
<br>
This is another line
</span>

If you are wanting to 'outline' the text as if it was a stroke and not a background you could use the -webkit-text-stroke element style.

You would first need to wrap the text in a html tag, e.g

or and apply a class to it.

<p class="textOutline">
This is a line
<br>
This is another line
</p>

Then apply the webkit-text-stroke style:

.textOutline {
webkit-text-stroke: #000;
    -webkit-text-stroke-width: medium;
}

Be aware this may not work or display differently in older browsers.

You could also apply the background as you have done above ^ and reduce the padding around the element to bring the background closer to the text. This would't appear like a stroke ^ but it would be closer than what you have now.

Related