2024-05-11|閱讀時間 ‧ 約 24 分鐘

CSS-position

    今天來介紹一下比較常用的4種定位方式
    其中讓我最搞混的是relative跟absolute

    position: relative

    在尚未設定top、bottom、left、right屬性時,看起來是static。然而,一旦設定了這些屬性,relative定位將會相對於元素原先的位置進行調整。

    position: absolute

    將一個元素的位置屬性設為 absolute 時,他會往外去找 position 不是 static 的層當參照點進行定位,若無則相對於整個網頁。這樣可以精確控制元素的位置,而不受其他元素的影響。

    position: fixed

    其參考點為 viewport 元素。你可以使用top、bottom、left、right這些屬性來指定元素的確切位置,他的作用就是不管你畫面滑到哪裡他都會在你的視窗。

    position: sticky

    其的參考點是離他最近的父元素,跟fixed有點像,不一樣的是sticky一開始不會出現,而是要捲動到此元素超過該畫面時,sticky 才會有作用把這個元素固定在畫面。


    <body>
    <div class="container">
    <div class="static-box">static Box</div>
    <div class="relative-box">Relative Box 是以container為基準 </div>
    <div class="absolute-box">Absolute Box 是以container為基準</div>
    <div class="fixed-box">Fixed Box 我是以BODY為基準</div>
    <div class="sticky-box">Sticky Box</div>
    </div>
    </body>


    body {
    margin: 0;
    font-family: Arial, sans-serif;
    width: 50vw;
    border: 3px green solid;
    margin-left: 5rem;
    }

    .container {
    width: 1200px;
    height: 1200px;
    background-color: #f0f0f0;
    border: 2px solid #000;
    position: relative;
    left: 80px;
    }

    .static-box {
    border: 2px solid orange;
    width: 70px;
    }

    .relative-box {
    position: relative;
    top: 10px;
    left: 20px;
    border: 2px solid red;
    width: 242px;
    }

    .absolute-box {
    position: absolute;
    top: 90px;
    left: 150px;
    border: 2px solid blue;
    }

    .fixed-box {
    position: fixed;
    top: 0px;
    left: 0px;
    background-color: #9999ff;
    }

    .sticky-box {
    position: sticky;
    top: 500px;
    background-color: #ffff99;
    padding: 10px;
    margin-bottom: 400px;
    }


    可以看看會更清楚!!


    分享至
    成為作者繼續創作的動力吧!
    從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

    發表回應

    成為會員 後即可發表留言
    © 2024 vocus All rights reserved.