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

By IncludeHelp Last updated : November 13, 2023

If you set background color to an element such as a paragraph, headings, etc, it will fill the color to the width of the entire element.

To set a background-color for the width of the text, not the width of the entire element, use an inline element such as <span> inside the specific element and then define the color to that incline element using the CSS's background-color property.

HTML Code

Add this HTML statement:

<h2><span>This is a heading element</span></h2>

CSS Code

Here the CSS code to perform this task:

h2 span {
  background-color: #006699;
}

Example

In this example, we have two heading elements (<h2> and <h3>). Inside the <h2> element, we placed an inline element (<span>), and <h3> element is without having any inline element.

<!DOCTYPE html> 
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width initial-scale=1.0" />
    <title>Document's Title</title>
    <style type="text/css">
      body{
      max-width: 1024px;
      margin: auto;
      font-family: Arial;
      }
      h2 span{
      background-color: #006699;
      }
      h3{
      background-color: #006969;
      }
    </style>
  </head>
  <body>
    <h2><span>This is a heading element</span></h2>
    <h3>Another heading</h3>
  </body>
</html>

Output

The output of the above example is:

set a background-color for the width of text

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.