div水平垂直居中位置:CSS fixed固定元素

12 月 23, 2019 | CSS, | 0 條留言

想製作一個以動態寬度和高度為中心的彈出框嗎?

使用css transform屬性

css transform這是一種使元素具有動態寬度水平居中的現代方法-適用於所有現代瀏覽器;支持可以在這裡看到

.jqbox_innerhtml {
    position: fixed;
    left: 50%;
    transform: translateX(-50%);
}

範例展示

對於垂直居中和水平居中,都可以使用以下方法:

.jqbox_innerhtml {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

範例展示

css transform是使用縮放元素的方式達到這個<div>水平垂直居中位置目的,缺點在他縮放到太小的裝置則會出現畫面模糊的情形,這在自適應的設計上會碰到的問題。以下的另有其他方法:

margin-topmargin-left減去<div>高度和寬度

您需要設置<div>top並將left其50%居中放置在<div>的左上角。您還需<div>的高度和寬度設置margin-topmargin-left,減去<div>的高度和寬度的一半,以將中心移到<div>的中間。

position: fixed;
width: 500px;
height: 200px;
top: 50%;
left: 50%;
margin-top: -100px; /* Negative half of height. */
margin-left: -250px; /* Negative half of width. */

要讓此固定的區塊自適應RWD任何裝置,可設置區塊width寬度時使用百分比%,如width:80%

position: fixed;
width: 80%;
height: 200px;
top: 50%;
left: 50%;
margin-top: -100px; /* Negative half of height. */
margin-left: -40%; /* Negative half of width. */

Demo

See the Pen Center a position:fixed element by Leon Cheng (@jq153387) on CodePen. 或者,如果你不關心垂直和舊的瀏覽器,如IE6 / 7為中心,那麼你就可以代替也增加left: 0,並right: 0,以該元素具有margin-left和margin-right的auto,使得具有fixed寬度的固定定位的元素知道在哪裡的左,右偏移開始。

position: fixed;
width: 500px;
height: 200px;
margin: 5% auto; /* Will not center vertically and won't work in IE6/7. */
left: 0;
right: 0;

參考:Center a position:fixed element