Home >Web Front-end >CSS Tutorial >How Can I Apply a Background Color to Text in an Element Without Affecting the Entire Page Width?

How Can I Apply a Background Color to Text in an Element Without Affecting the Entire Page Width?

DDD
DDDOriginal
2024-12-01 00:38:12795browse

How Can I Apply a Background Color to Text in an  Element Without Affecting the Entire Page Width?

Background Color for Text Width Only in CSS

You wish to apply a green background behind the text in an

element, but not span the entire page width. Your current code below won't achieve that:

<h1>
  The Last Will and Testament of Eric Jones
</h1>
h1 { 
  text-align: center; 
  background-color: green; 
}

Since you cannot modify the HTML to include an inline element like a , the solution is to convert the text into an inline element. This can be achieved by wrapping the text in a element and applying the green background color to it:

<h1>
  <span>The Last Will and Testament of Eric Jones</span>
</h1>
h1 {
  text-align: center; 
}
h1 span { 
  background-color: green; 
}

Inline elements only span the width of their content, ensuring that the green background only appears behind the text, not the entire page.

The above is the detailed content of How Can I Apply a Background Color to Text in an Element Without Affecting the Entire Page Width?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn