<div class="parent">
<div class="child">第一个div</div>
<div class="child center-me">第二个div</div>
</div>
<style>
.parent {
position: relative;
height: 100vh; /* 假设父div占满视口高度 */
}
.center-me {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* 偏移自身宽高的一半以实现居中 */
}
</style>
这种方法将第二个 div
绝对定位到父 div
的中心,并通过 transform
属性调整其位置,以使其完全居中。然而,这种方法可能会影响到页面上的其他元素(如覆盖在它们之上),因此在使用时需要谨慎,但如果附近位置没其他元素则是一个非常直观的解决思路。