寫了好幾年網頁,卻一直是CSS新手,最近一年才比較認真研究個中奧妙,也慢慢解開一些原本搞不定的小眉角,說穿了不複雜,但相信我肯定不是地球最後一個發現的網頁攻城獅,故筆記分享,如高手發現有誤或另有妙法,請不吝指正。

我對於position: absolute的認識是很粗淺的,印象還停留在ASP.NET 1.1時代WebForm的Grid Layout Mode,啟用後網頁的控制項會變成像Window Form一樣採絕對座標,可拖拉擺放到任意位置。當時知道背後是透過position: absolute再加上top、left等CSS設定完成的,近十年下來一直以為所謂的position: absolute就是"以整個網頁為座標基準擺放元素"。

直到最近,我才學習到: position: absolute的定址基準,不一定是整個網頁,也可以相對於父元素;另外,定址依據並非只有top及left,還有right及bottom,如以下的例子:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>position absolute的應用</title>
  <style>
  #out,#in { border: 2px solid gray; }
  #out {
      margin: 100px;
      background-color: #ddd;
      width: 200px;
      height: 200px;
      position: relative;
  }
  #in {
      background-color: red;
      width: 50px;
      height: 50px;
      position: absolute;
      right: 10px; bottom: 10px;
  }    
  </style>
</head>
<body>
  <div id="out">
  <div id="in"></div>
  </div>  
</body>
</html>

內部的紅色<div>被設為position: absolute、right: 10px、bottom: 10px,便可將其定位在灰色容器<div>右下角。線上展示

但其中有點要注意,灰方塊必須設定成position: relative,紅方塊才會以它計算座標,要是拿掉relative設定,紅方塊會變成貼在整張網頁的右下角。線上展示

position: absolute的文件,說明了此一行為的依據:

Absolute positioning

Elements that are positioned relatively are still considered to be in the normal flow of elements in the document. In contrast, an element that is positioned absolutely is taken out of the flow and thus takes up no space when placing other elements. The absolutely positioned element is positioned relative to nearest positioned ancestor. If a positioned ancestor doesn't exist, the initial container is used.

關鍵在其容器或其再上層的容器元素是否為"positioned ancestor",如果不是,便會以"initial container"(<body>,也就是整張網頁)為準。而positioned元素的定義為: an element whose computed position property is relative, absolute, or fixed. 這就是灰方塊設定relative才能成為紅方塊定位基準的理由。

而以上特性,還可做出單靠CSS實現隨容器尺寸自動放大縮小的效果! 紅方格不要指定width、height,透過position: absolute並指定top/left/right/bottom,就能產生類似Window Form Docking+Margin的結果: 線上展示

雖然自己都覺得Lag嚴重,但現在學會總比還不知道好,哈!


Comments

# by Dennis

文章標題的absolute打錯了XD

# by Jeffrey

to Dennis, 謝謝指正。希望CSS之神沒有生氣,詛咒我以後調元素位置永遠都差1個Pixel~ XD

# by stevem

我已哭.......感謝大大............................解決我的問題.................愛你~~~

Post a comment