How to set paragraph width automatically in CSS?

user2020058 picture user2020058 · Jun 18, 2013 · Viewed 94.6k times · Source

Here's the deal. Instead of just underlining my paragraph and using text-align, I want to add a dotted border underneath and center it inside the paragraph's parent div. This is my code that is not working. (It adds the border across the whole div instead of just the paragraph)

p {
  border-bottom:1px dotted;
  margin-left:auto;
  margin-right:auto;
  text-align:center;
}

The paragraph seems to be taking on the width of the parent div. Is there a way to set the paragraph's width to the text it contains? (It seems that margin:auto would work if possible.)

Answer

SlightlyCuban picture SlightlyCuban · Jun 18, 2013

Paragraphs are going to expand to the width of their containers. To make it not do that, you could try:

p { display: inline-block; }

Fiddle with example: http://jsfiddle.net/HuFZL/1/

Also, you may want to wrap the p tags in an additional div, if you need them to clear other paragraphs/elements.