使用 CSS 絕對定位 讓元素置中

1. 使用 margin: auto; + top、bottom、left、right

這種方式適用於 已知寬高的元素,並且 父元素是 position: relative;。

HTML

<div class="outer">
    <div class="inner1">置中的元素</div>
</div>

CSS

.inner1 {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;

    /*設定元素的寬高*/
    width: 100px;
    height: 100px;
    
    /*設定元素內的字*/
    background: skyblue;
    text-align: center;
    line-height: 100px;
    color: white
}
置中的元素

2. 使用 top、left + transform

這種方式適用於 父元素是 position: relative; 或 視窗(使用 position: fixed;) 的情況。
  1. 設定 position: absolute;(相對於父元素)。
  2. 設定 top: 50%; left: 50%;,讓元素左上角對齊父元素的中心點。
  3. 使用 transform: translate(-50%, -50%);,讓元素自身的中心對齊父元素的中心。

HTML

<div class="outer">
    <div class="inner2">置中的元素</div>
</div>

CSS

.inner2 {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 100px;
    height: 100px;
    background: darkgreen;
    text-align: center;
    line-height: 100px;
    color: white;
}
置中的元素