我试图将 div 居中对齐,但 text-align: center 和 margin: 0 auto 似乎都不适用于绝对定位的元素。我假设两者都不适用于绝对定位的元素。这种情况我该怎么办?
#wrap {
border: 1px solid black;
position: relative;
width: 500px;
height: 250px;
margin: 0 auto;
text-align: center;
}
#absolute {
border: 1px solid red;
position: absolute;
display: block;
bottom: 0;
margin: 0 auto;
cursor: pointer;
}
<div id='wrap'>
<div id='absolute'>Click Me</div>
</div>
最佳答案
在不更改 HTML 的情况下,使元素水平居中的最简单方法是将 left: 50%
和 transform: translateX(-50%)
结合起来。这实际上会将元素 50%
定位到右侧,然后通过将其 -50%
转换到左侧来替换元素宽度的一半。这样做时,无论宽度如何,元素都将水平居中,这意味着您不需要对任何值进行硬编码。
position: absolute;
left: 50%;
transform: translateX(-50%);
更新的代码片段:
#wrap {
border: 1px solid black;
position: relative;
width: 500px;
margin: 0 auto;
height: 80px;
}
#absolute {
border: 1px solid red;
position: absolute;
transform: translateX(-50%);
left: 50%;
bottom: 0;
cursor: pointer;
}
<div id="wrap">
<div id="absolute">Click Me</div>
</div>
或者,如果您可以更改 HTML,只需将 left: 0
和 right: 0
添加到绝对定位的 element 元素中,即可使其宽度为父容器。然后您可以添加 text-align: center
以使子元素居中:
更新的代码片段:
#wrap {
border: 1px solid black;
position: relative;
width: 500px;
margin: 0 auto;
height: 80px;
}
#absolute {
position: absolute;
left: 0; right: 0;
bottom: 0;
text-align: center;
}
#absolute > span {
border: 1px solid red;
cursor: pointer;
}
<div id="wrap">
<div id="absolute">
<span>Click Me</span>
</div>
</div>
关于javascript - 文本对齐 :center and margin:0 auto not working on absolute positioned elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35353500/