4.2 position

  • static

.static {
  position: static;
}
  • relative

.relative1 {
  position: relative;
}
.relative2 {
  position: relative;
  top: -20px;
  left: 20px;
  background-color: white;
  width: 500px;
}
  • absolute

absolutefixed 的行為很像,不一樣的地方在於 absolute 元素的定位是在他所處上層容器的相對位置。如果這個套用 position: absolute 的元素,其上層容器並沒有「可以被定位」的元素的話,那麼這個元素的定位就是相對於該網頁所有內容(也就是 <body> 元素)最左上角的絕對位置,看起來就是這張網頁的絕對位置一樣,所以當你的畫面在捲動時,該元素還是會隨著頁面捲動。請記得,只有套用 position: static 的元素屬於「不會被特別定位」的元素,套用 static 以外的屬性值都算是「可以被定位」的元素。

.relative {
  position: relative;
  width: 600px;
  height: 400px;
}
.absolute {
  position: absolute;
  top: 120px;
  right: 0;
  width: 300px;
  height: 200px;
}
  • fixed

固定定位(position: fixed)的元素會相對於瀏覽器視窗來定位,這意味著即便頁面捲動,它還是會固定在相同的位置。和 relative 一樣,我們會使用 toprightbottomleft 屬性來定位。

Last updated

Was this helpful?