user3067088 user3067088 - 1 year ago 72
CSS Question

CSS: set width equal to content

I'm experiencing some troubles with the width property of CSS. I have some paragraphs inside a div. I'd like to set the width of the paragraphs equal to their content, so that their green background looks like a label for the text. What I get instead is that the paragraphs inherit the width of the div father node which is wider. What I am supposed to do?
Thank you.


<div id="container">
<p>Sample Text 1</p>
<p>Sample Text 2</p>
<p>Sample Text 3</p>


#container {
width: 30%;
background-color: grey;
#container p{
background-color: green;

Answer Source

Hi p tags are for default block elements that means he take the 100% of the parent width.

You can change your display property :

#container p {

But it makes element side by side to keep each element in one line you can use :

#container p {

If you use float need to clear after floated elements see in this link different techniques

The demo


If you go for the solution with display:inline-block and want to keep each item in one line also can add <br> tag at the end of each one:

<div id="container">
  <p>Sample Text 1</p><br/>
  <p>Sample Text 2</p><br/>
  <p>Sample Text 3</p><br/>

New demo