我希望我的<p>
元素位于容器<div>
的中心,就像完全居中一样--顶部、底部、左侧和右侧的页边距平均地分割空格。
我怎样才能做到这一点呢?
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>
发布于 2013-02-28 04:19:53
将左/右居中,然后将text-align: center
应用于div
,将margin: auto
应用于p
。
对于垂直定位,你应该确保你理解不同的方法,这是一个常见的问题:Vertical alignment of elements in a div
发布于 2019-03-06 03:53:21
在p元素上,添加3个样式规则。
.myCenteredPElement{
margin-left: auto;
margin-right: auto;
text-align: center;
}
发布于 2020-03-12 23:06:54
此解决方案适用于除IE以外的所有主要浏览器。所以请记住这一点。
在本例中,我基本上使用了定位、水平和垂直变换来使UI元素居中。
.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)));
}
<div class="container">
<p class="paragh">Text</p>
</div>
我希望这能有所帮助。
https://stackoverflow.com/questions/15121343
复制相似问题