Search code examples
htmlcssbackground-colorparagraph

How to apply background colour property to only the area on which the text is located?


I have a div block inside which I have a paragraph whose background is black:

<!DOCTYPE html>
<html>
    <head>
        <style>
            div {
                background-color: black;
                color: white;
                text-align: center;
                font-size: 50px;
            }
        </style>
    </head>
    <body>
        <div>
            <p>Paragraph</p>
        </div>
    </body>
</html>

The output of the above code is this: enter image description here



I want the background colour to be only applied to the area on which the text of the paragraph is located, like this: enter image description here

I have no idea how to achieve that effect. Can anyone tell me what to do? (P.S. Can you also tell me how to round the corners?)


Solution

  • Make <p> an inline-block element and give it a background color:

    div {
      color: white;
      text-align: center;
      font-size: 50px;
    }
    
    p {
      background-color: black;
      display: inline-block;
    }
    <div>
      <p>Paragraph</p>
    </div>

    If <div> is just a wrapper, then you can do it even easier:

    div {
      width: min-content;
      margin: 0 auto;
      background-color: black;
      color: white;
      font-size: 50px;
    }
    <div>
      <p>Paragraph</p>
    </div>