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>
在顶部,但我无法使用
<center>
或margin: 0 auto
来使其居中。如果您为 div
设置一个固定的宽度,问题可能会得到解决,方法如下:
div#thing {
position: absolute;
top: 0px;
z-index: 2;
width:400px;
margin-left:-200px;
left:50%;
}
div#thing
{
position: absolute;
width:400px;
right: 0;
left: 0;
margin: auto;
}
我知道我来晚了,但我想为那些需要在水平方向上定位绝对元素的人提供一个答案,即使你不知道它的确切宽度。
试试这个方法:
// Horizontal example.
div#thing {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
同样的技术也可以应用于需要垂直对齐的情况,只需调整属性即可:
// Vertical example.
div#thing {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
div#thing {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.contentBlock {
width: {define width}
width: 400px;
position: absolute;
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
}
我遇到了同样的问题,我的限制是不能有预定义的宽度。如果您的元素没有固定的宽度,请尝试这个方法
div#thing
{
position: absolute;
top: 0px;
z-index: 2;
left:0;
right:0;
}
div#thing-body
{
text-align:center;
}
<div id="thing">
<div id="thing-child">
<p>text text text with no fixed size, variable font</p>
</div>
</div>
或者你可以使用相对单位,例如:
#thing {
position: absolute;
width: 50vw;
right: 25vw;
}
div#wrapper {
position: absolute;
width: 100%;
text-align: center;
}
请记住,为了绝对定位一个元素,父元素必须相对定位。
是的:
div#thing { text-align:center; }