How to apply background-color to the HTML element p?

-1

I need to apply the CSS property background-color to the HTML element p but what is happening is that this background-color takes the entire width of a div for example if it is the parent element and not only colors the element p .

What I have:

WhatIneed:

    
asked by anonymous 09.11.2014 / 15:23

3 answers

4

Put the specific text inside the tag span and leave your CSS as follows:

<html>
  <head>
    <title>TODO supply a title</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
      p span{
        background-color: blue;
      }
    </style>
  </head>
  <body>
    <div><p><span>PARAGRAFO</span></p></div>
  </body>
</html>

I did the test here and it worked fine.

    
09.11.2014 / 15:40
7

Solution via CSS

The solution depends on the remainder of your markup , but if you have a <p/> within a <div/> , without adding more markup you can assign the property display to your paragraph:

p{
    background-color:orange;
    display:inline-block;    /* deixa de ser bloco e passa a bloco de linha */
}

In this way markup stays the same and you make use of CSS properties to adjust the display of the element.

In detail

By default the <p/> element is displayed as a block, which causes it to occupy the full width of the screen.

When we apply the display property to the value inline-block in the CSS, we mean that we want <p/> to be displayed as a line block whose characteristic is that its width is not greater than width of your content unless otherwise specified.

Example

p{
    background-color:orange;
    display:inline-block;
}
<div>
  <p>CONSULTÓRIO</p>
</div>
    
09.11.2014 / 16:06
5

Your CSS is working perfectly fine, just missing understanding how <p> works. By default, the width of a paragraph is 100%, even though the text in it does not take up all the width.

To achieve the desired effect, simply change this characteristic with float:left , or even display:inline-block . Here is a functional example:

.reduzido { float:left; background-color: #fc9 }

.texto { clear:both }
<p class="reduzido">CONSULTÓRIO</p>

<p class="texto">Texto texto texto texto texto texto texto.</p>

In this way you do not have to de-structure your original HTML to get the desired effect, and the element continues with the block characteristics. Note that it is convenient to use clear:both or at least clear:left in the next element to ensure that it starts on the bottom line. With the space for other things after the paragraph, other elements can be on the same line without clear .

    
09.11.2014 / 16:12