首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在<div>容器中居中放置<p>元素?

如何在<div>容器中居中放置<p>元素?
EN

Stack Overflow用户
提问于 2013-02-28 04:06:51
回答 4查看 168.2K关注 0票数 50

我希望我的<p>元素位于容器<div>的中心,就像完全居中一样--顶部、底部、左侧和右侧的页边距平均地分割空格。

我怎样才能做到这一点呢?

代码语言:javascript
复制
div {
  width: 300px;
  height: 100px;
}
p {
  position: absolute;
  top: auto;
}
代码语言:javascript
复制
<div>
  <p>I want this paragraph to be at the center, but it's not.</p>
</div>

EN

回答 4

Stack Overflow用户

发布于 2013-02-28 04:19:53

将左/右居中,然后将text-align: center应用于div,将margin: auto应用于p

对于垂直定位,你应该确保你理解不同的方法,这是一个常见的问题:Vertical alignment of elements in a div

票数 13
EN

Stack Overflow用户

发布于 2019-03-06 03:53:21

在p元素上,添加3个样式规则。

代码语言:javascript
复制
.myCenteredPElement{
    margin-left:  auto;
    margin-right: auto;
    text-align: center;
}
票数 0
EN

Stack Overflow用户

发布于 2020-03-12 23:06:54

此解决方案适用于除IE以外的所有主要浏览器。所以请记住这一点。

在本例中,我基本上使用了定位、水平和垂直变换来使UI元素居中。

代码语言:javascript
复制
        .container {
            /* set the the position to relative */
            position: relative;
            width: 30rem;
            height: 20rem;
            background-color: #2196F3;
        }


        .paragh {
            /* set the the position to absolute */
            position: absolute;
            /* set the the position of the helper container into the middle of its space */
            top: 50%;
            left: 50%;
            font-size: 30px;
            /* make sure padding and margin do not disturb the calculation of the center point */
            padding: 0;
            margin: 0;
            /* using centers for the transform */
            transform-origin: center center;
            /* calling calc() function for the calculation to move left and up the element from the center point */
            transform: translateX(calc((100% / 2) * (-1))) translateY(calc((100% / 2) * (-1)));
        }
代码语言:javascript
复制
<div class="container">
    <p class="paragh">Text</p>
</div>

我希望这能有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15121343

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档