How to Set a Background Color for Text Width Using CSS
In your quest to create a green background behind only your text and not the entire page width, you're facing a challenge. Here's how to navigate this situation while respecting the constraints you mentioned:
Solution: Envelop Your Text in an Inline Element
Since you cannot modify the HTML, wrap your text in an inline element, such as a .
<h1><span>The Last Will and Testament of Eric Jones</span></h1>
Now, you can apply the background color to the inline element:
h1 { text-align: center; } h1 span { background-color: green; }
The Rationale:
Inline elements shrink to fit their content, ensuring that the background color aligns perfectly with the text width. This technique allows you to create a background effect specifically for your text without impacting the surrounding elements.
The above is the detailed content of How Can I Add a Background Color Only to Text Using CSS?. For more information, please follow other related articles on the PHP Chinese website!