0

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?)

Yash Chitroda
  • 645
  • 4
  • 8
  • 27
pr0grammar
  • 107
  • 10

4 Answers4

3

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>
UModeL
  • 1,217
  • 1
  • 10
  • 15
1

Do something like this set the parent element width to width: max-content.

div {
  background-color: black;
  color: white;
  text-align: center;
  font-size: 50px;
  position: relative;
  width: max-content;
}
<div>
  <p>Paragraph</p>
</div>

And for rounding the corners set border-radius: 2px or change the value to how round you want.

div {
  background-color: black;
  color: white;
  text-align: center;
  font-size: 50px;
  position: relative;
  width: max-content;
  border-radius: 4px;
}
<div>
  <p>Paragraph</p>
</div>
Kunal Tanwar
  • 1,209
  • 1
  • 8
  • 23
0

<!DOCTYPE html>
<html>
    <head>
        <style>
            div {
                background-color: black;
                color: white;
                text-align: center;
                font-size: 50px;
            }
        </style>
    </head>
    <body>
        <div>
            <p><span style="background-color:blue;border-radius: 4px" >Paragraph</span></p>
        </div>
    </body>
</html>
  • I think you misunderstood the question. I only wanted to apply the background colour to the text (as you have applied the blue colour). But the black colour around the paragraph covering the empty space is unnecessary and I wanted to do away with that. – pr0grammar Aug 14 '21 at 08:05
0

You don't need to write extra css for p tag. You can also achieve this behavior by using div css only.

div {
  background-color: black;
  color: white;
  font-size: 50px;
  position: relative;
  width: max-content;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}
<div>
  <p>Paragraph</p>
</div>
Yogesh Yadav
  • 723
  • 6
  • 21