iT邦幫忙

2024 iThome 鐵人賽

DAY 20
0

position 是 CSS 中用來控制元素佈局和定位的屬性,根據不同的方式來控制元素的位置
今天主要介紹以下五種值:
static
relative
absolute
fixed
sticky

  1. static預設值,不會改變元素的定位方式
position: static;

https://ithelp.ithome.com.tw/upload/images/20240925/20168468lzxkZtbLmi.png
可透過以上這張圖得知,兩個方塊會依照瀏覽器預設的配置自動排版在頁面上,位置不變。

  1. relative(相對定位)元素相對於其正常位置進行移動,可使用top、right、bottom、left 來進行調整
position: relative;
top: 20px;
left: 30px;

https://ithelp.ithome.com.tw/upload/images/20240925/20168468SDyCtdfdYx.png
relative 表現的和 static 一樣,除非你增加了一些額外的屬性,像是top、right、bottom、left,
這樣就會根據你的調整做改變。

  1. absolute(絕對定位)脫離文檔流,並相對其最近的有定位的父元素進行絕對定位
position: absolute;

https://ithelp.ithome.com.tw/upload/images/20240925/20168468on7XUrnNU2.png
absolute很特別,因為他會根據父元素進行定位,而這張圖的父元素為外圍的黑色框線,所以裡面的方塊會依照父元素做位置的定位。

  1. fixed不隨頁面滾動而改變位置
position: fixed;

https://ithelp.ithome.com.tw/upload/images/20240925/20168468Hq1hONChcZ.png
無論滾軸如何移動,Fixed Box永遠都只會固定在最頂部。

  1. sticky元素在特定的滾動位置之前是相對定位的,達到該位置後變為固定定位
position: sticky;

https://ithelp.ithome.com.tw/upload/images/20240925/201684681dLBwGGsDH.png
https://ithelp.ithome.com.tw/upload/images/20240925/201684680v7hxiFZhe.png
第一張圖為未滾動滾軸前,有兩行字在最頂部,但再看看第二張圖,滾軸移動到一定的位置,第二行字就會消失,
這也是sticky特別的地方。

/images/emoticon/emoticon29.gif


上一篇
Day19.CSS<background>屬性
下一篇
Day21.CSS<hover>效果
系列文
Web前端的探索:30天的驚奇之旅22
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言