Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center a <p> element inside a <div> container?

I want my <p> element to be at the center of a container <div>, as in perfectly centered -- the top, bottom, left and right margins split the spaces equally.

How can I achieve that?

div {    width: 300px;    height: 100px;  }  p {    position: absolute;    top: auto;  }
<div>    <p>I want this paragraph to be at the center, but it's not.</p>  </div>
like image 648
Johnsy Avatar asked Feb 27 '13 20:02

Johnsy


People also ask

How do I center a P inside a div?

You can do this by setting the display property to “flex.” Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.

How do you center a P element in CSS?

To center text in CSS, use the text-align property and define it with the value 'center.


1 Answers

You dont need absolute positioning Use

p {  text-align: center; line-height: 100px;  } 

And adjust at will...

If text exceeds width and goes more than one line

In that case the adjust you can do is to include the display property in your rules as follows;

(I added a background for a better view of the example)

div {   width:300px;   height:100px;     display: table;    background:#ccddcc;   }   p {   text-align:center;    vertical-align: middle;   display: table-cell;    } 

Play with it in this JBin

enter image description here

like image 147
Fico Avatar answered Sep 29 '22 11:09

Fico