div#thing {
position: absolute;
top: 0px;
z-index: 2;
margin: 0 auto;
}
<div id="thing">
<p>text text text with no fixed size, variable font</p>
</div>
Run Code Online (Sandbox Code Playgroud)
股利是在顶部,但我不能居中<center>
或margin: 0 auto
;
Jac*_*obE 148
如果您给出div
固定宽度,可能会解决您的问题,如下所示:
div#thing {
position: absolute;
top: 0px;
z-index: 2;
width:400px;
margin-left:-200px;
left:50%;
}
Run Code Online (Sandbox Code Playgroud)
小智 96
div#thing
{
position: absolute;
width:400px;
right: 0;
left: 0;
margin: auto;
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*umo 32
我知道我迟到了,但我想我会在这里为需要水平放置绝对物品的人提供答案,当你不知道它的确切宽度时.
试试这个:
// Horizontal example.
div#thing {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
Run Code Online (Sandbox Code Playgroud)
同样的技术也可以应用,因为当您可能需要垂直对齐时,只需调整属性如下:
// Vertical example.
div#thing {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
Run Code Online (Sandbox Code Playgroud)
要垂直和水平居中,请执行以下操作:
div#thing {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
Run Code Online (Sandbox Code Playgroud)