问题
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>
回答1:
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

回答2:
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
回答3:
♣you should do these steps :
- the mother Element should be positioned(for EXP you can give it position:relative;)
- the child Element should have positioned "Absolute" and values should set like this: top:0;buttom:0;right:0;left:0; (to be middle vertically)
- for the child Element you should set "margin : auto" (to be middle vertically)
- the child and mother Element should have "height"and"width" value
- for mother Element => text-align:center (to be middle horizontally)
♣♣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;
}
回答4:
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>
I fiddled it here
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;
}
jsfiddle.net/9Mk64/
回答5:
on the p element, add 3 styling rules.
.myCenteredPElement{
margin-left: auto;
margin-right: auto;
text-align: center;
}
回答6:
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
来源:https://stackoverflow.com/questions/15121343/how-to-center-a-p-element-inside-a-div-container