Open In App

How to add Background-Color for Text Width Instead of Entire Element Width using CSS ?

Last Updated : 23 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to add background color for the text width instead of the entire element width using CSS. 

The display: inline or display: inline-block property is used to set the background color of the text width. 

Syntax:

display: inline;  
display: inline-block;

Approach: We will create an element and then apply the display: inline or display: inline-block property value to set the background color for the text width. The inline value is used to display an element as an inline element and the inline-block element is used to display an element as an inline-level block container.

Example 1: The following code demonstrates the above approach with display: inline-block property value.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
    <title>
        How to add Background-Color for
        Text Width Instead of Entire
        Element Width using CSS ?
    </title>
  
    <style>
        body {
            text-align: center;
        }
        h1 {
            color: green;
        }
        h2 {
            display: inline-block; 
            background-color: green;
        }
    </style>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
  
    <h3>
        How to add Background-Color for
        Text Width Instead<br> of Entire
        Element Width using CSS ?
    </h3>
  
    <h2>Web Technology</h2>
</body>
  
</html>


Output:

 

Example 2: The following code demonstrates the above approach with display: inline property value applied on the span elements.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
    <title>
        How to add Background-Color for
        Text Width Instead of Entire
        Element Width using CSS ?
    </title>
  
    <style>
        body {
            text-align: center;
        }
        h1 {
            color: green;
        }
        span {
            display: inline; 
            background-color: green;
            color: white;
            padding: 10px;
        }
    </style>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
  
    <h3>
        How to add Background-Color for
        Text Width Instead<br> of Entire
        Element Width using CSS ?
    </h3>
  
    <p>
        <span>Web Technology</span>
        <span>HTML</span>
        <span>CSS</span>
        <span>JavaScript</span>
    </p>
</body>
  
</html>


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads