--- tags: CSS, 六角筆記王 title: CSS - position --- # CSS - position 定位,在切版時是很重要的屬性,好的定位可以做出更具風格的版型,目前它有這些屬性可以使用: | 屬性值 | 功能 | | -------- | -------- | | static | 預設值,無須加入 position 屬性就會有 | | relative | 相對定位,以自己為基準位置 | | absolute | 絕對定位,以父層為基準位置 | | fixed | 固定位置 | | sticky | 混和相對與固定 | 除了預設值外,當加入了其他四項屬性值後,以下屬性才會有作用並可以設定單位值 : - `top` - `bottom` - `left` - `right` ## position : relative 相對定位,設定後 : - 以自己為基準位置 - 區塊疊加,例如區塊元素往下排列 - 若被設定的對象是行內元素,往下排列時,寬度會依行內元素為主 - 寬度繼承父層 ```sass // 以自己的頂部為基準推 50px 距離 .content { position: relative; top: 50px; } ``` <iframe height="300" style="width: 100%;" scrolling="no" title="六角筆記王 - CSS - 絕對定位 相對定位" src="https://codepen.io/hsuan333/embed/zYweKaL?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/hsuan333/pen/zYweKaL"> 六角筆記王 - CSS - 絕對定位 相對定位</a> by Vic (<a href="https://codepen.io/hsuan333">@hsuan333</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ## position : absolute 絕對定位,設定後 : - 父層為基準位置 - 寬度未繼承父層 - 若同時設定了 relative - 也會以自己為基準 - 但上下左右之距離則以父層為基準 ```sass // 以父層頂部為基準推 10px 距離,自己的偽元素從頂部推 10px 距離 // 若以自己為基準,大部分都是使用偽元素較多 // 也就是說,大部分看到定位都是成對出現,但其實它們本來就是獨立的 .contentB { position: relative; position: absolute; top: 50px; &::after { position: absolute; content: "123"; top: 10px; } } ``` ## position : fixed 固定位置,隨設定值而後固定在頁面中,若: - 不設定,按照原本標籤元素排列,沒有固定效果 - 有設定 `top` 等屬性,依據頁面上下左右為基準,位置不會改變 ```sass // 固定在頁面中 .content { position: fixed; bottom: 0; } ``` ## position : sticky 混和相對與固定,隨設定值而後固定在頁面中,若: - 不設定,按照原本標籤元素排列,沒有固定效果 - 有設定 `top` 屬性,超過畫面頂部時,會被固定住 ```sass // 固定在頁面中 .content { position: sticky; top: 0; } ``` ## 參考來源 > 1. [冠穎的筆記本 - 鼠年全馬鐵人挑戰 02:容易誤解的 position 特性](https://bryanchu10.github.io/blog/2020/03/29/2020-03-29-%20position/) > 2. [Will 保哥 翻譯 - 學習 CSS 版面配置](https://zh-tw.learnlayout.com/position.html) > 3. [Sandy - position 屬性的基礎概念](https://medium.com/ui-ux%E7%B7%B4%E5%8A%9F%E5%9D%8A/position-%E5%B1%AC%E6%80%A7%E7%9A%84%E5%9F%BA%E7%A4%8E%E6%A6%82%E5%BF%B5-5931254e5203)