如何将两个元素放在``元素的中心[英]How to position two elements at the center of a `` element 本文翻译自  MLister  查看原文  2012-08-15  1216    layout/

时间:2021-10-05 20:30:50

I have two <p> elements inside a <div> element, and want to position them at the center of the <div> element. e.g.

我在

元素中有两个

元素,并希望将它们放在

元素的中心。例如

<div id="mydiv">
   <p class="above">some text</p>
   <p class="below">other text</p>
</div>

Note: the <div> element itself is not positioned at the center of the browser window, so the positioning of <p> elements is only relative.

注意:

元素本身不位于浏览器窗口的中心,因此

元素的位置只是相对的。

4 个解决方案

#1


1  

text-align: center;

for text.

用于文本。

margin: 0 auto;

for block level elements like a div.

块级元素,如div。

#2


1  

EDITED:

编辑:

Add following css rules in #mydiv

在#mydiv中添加以下css规则

display:table-cell;
vertical-align:middle;

Like This

喜欢这个

#mydiv{
    position:relative;
    border:1px solid #000;
    width:400px;
    height:300px;

    display:table-cell; /* Added rule - Note: IE8+, Firefox, Chrome, Opera, Safari */
    vertical-align:middle; /* Added rule */
}

#mydiv p{
    text-align:center;
}​

UPDATED DEMO

#3


0  

text-align: center;

It's worked for me.

它对我有用。

#4


-1  

You may try;

你可以尝试;

margin-left:auto;
margin-right:auto;

to your p

到你的p

Here is a Live Demo

这是一个现场演示

If you want to center both vertically and horizontally, you may try Dead Center

如果你想垂直和水平居中,你可以尝试死亡中心

Here is a demo showing centering a div Both Vertically and Horizontally

这是一个演示,显示垂直和水平居中的div

#1


1  

text-align: center;

for text.

用于文本。

margin: 0 auto;

for block level elements like a div.

块级元素,如div。

#2


1  

EDITED:

编辑:

Add following css rules in #mydiv

在#mydiv中添加以下css规则

display:table-cell;
vertical-align:middle;

Like This

喜欢这个

#mydiv{
    position:relative;
    border:1px solid #000;
    width:400px;
    height:300px;

    display:table-cell; /* Added rule - Note: IE8+, Firefox, Chrome, Opera, Safari */
    vertical-align:middle; /* Added rule */
}

#mydiv p{
    text-align:center;
}​

UPDATED DEMO

#3


0  

text-align: center;

It's worked for me.

它对我有用。

#4


-1  

You may try;

你可以尝试;

margin-left:auto;
margin-right:auto;

to your p

到你的p

Here is a Live Demo

这是一个现场演示

If you want to center both vertically and horizontally, you may try Dead Center

如果你想垂直和水平居中,你可以尝试死亡中心

Here is a demo showing centering a div Both Vertically and Horizontally

这是一个演示,显示垂直和水平居中的div