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 {_x000D_
width: 300px;_x000D_
height: 100px;_x000D_
}_x000D_
p {_x000D_
position: absolute;_x000D_
top: auto;_x000D_
}
_x000D_
<div>_x000D_
<p>I want this paragraph to be at the center, but it's not.</p>_x000D_
</div>
_x000D_
on the p element, add 3 styling rules.
.myCenteredPElement{
margin-left: auto;
margin-right: auto;
text-align: center;
}
This solution works fine for all major browsers, except IE. So keep that in mind.
In this example, basicaly I use positioning, horizontal and vertical transform for the UI element to center it.
.container {_x000D_
/* set the the position to relative */_x000D_
position: relative;_x000D_
width: 30rem;_x000D_
height: 20rem;_x000D_
background-color: #2196F3;_x000D_
}_x000D_
_x000D_
_x000D_
.paragh {_x000D_
/* set the the position to absolute */_x000D_
position: absolute;_x000D_
/* set the the position of the helper container into the middle of its space */_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
font-size: 30px;_x000D_
/* make sure padding and margin do not disturb the calculation of the center point */_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
/* using centers for the transform */_x000D_
transform-origin: center center;_x000D_
/* calling calc() function for the calculation to move left and up the element from the center point */_x000D_
transform: translateX(calc((100% / 2) * (-1))) translateY(calc((100% / 2) * (-1)));_x000D_
}
_x000D_
<div class="container">_x000D_
<p class="paragh">Text</p>_x000D_
</div>
_x000D_
I hope this help.
You only need to add text-align: center
to your <div>
In your case also remove both styles that you added to your <p>
.
Check out the demo here: http://jsfiddle.net/76uGE/3/
Good Luck
?you should do these steps :
??simply here is the summery of those 5 steps:
.mother_Element {
position : relative;
height : 20%;
width : 5%;
text-align : center
}
.child_Element {
height : 1.2 em;
width : 5%;
margin : auto;
position : absolute;
top:0;
bottom:0;
left:0;
right:0;
}
To get left/right centering, then applying text-align: center
to the div
and margin: auto
to the p
.
For vertical positioning you should make sure you understand the different ways of doing so, this is a commonly asked problem: Vertical alignment of elements in a div
Centered and middled content ?
Do it this way :
<table style="width:100%">
<tr>
<td valign="middle" align="center">Table once ruled centering</td>
</tr>
</table>
Ha, let me guess .. you want DIVs ..
just make your first outter DIV behave like a table-cell then style it with vertical align:middle;
<div>
<p>I want this paragraph to be at the center, but I can't.</p>
</div>
div {
width:500px;
height:100px;
background-color:aqua;
text-align:center;
/* there it is */
display:table-cell;
vertical-align:middle;
}
Source: Stackoverflow.com