【CSS新手筆記】小探position: absolute應用

寫了好幾年網頁,卻一直是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嚴重,但現在學會總比還不知道好,哈!

歡迎推文分享:
Published 22 July 2013 10:32 PM 由 Jeffrey
Filed under:
Views: 12,181



意見

# Dennis said on 22 July, 2013 09:13 PM

文章標題的absolute打錯了XD

# Jeffrey said on 23 July, 2013 05:11 AM

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

# stevem said on 23 September, 2016 05:18 AM

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

你的看法呢?

(必要的) 
(必要的) 
(選擇性的)
(必要的) 
(提醒: 因快取機制,您的留言幾分鐘後才會顯示在網站,請耐心稍候)

5 + 3 =

搜尋

Go

<July 2013>
SunMonTueWedThuFriSat
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910
 
RSS
創用 CC 授權條款
【廣告】
twMVC
最新回應

Tags 分類檢視
關於作者

一個醉心技術又酷愛分享的Coding魔人,十年的IT職場生涯,寫過系統、管過專案, 也帶過團隊,最後還是無怨無悔地選擇了技術鑽研這條路,近年來則以做一個"有為的中年人"自許。

文章典藏
其他功能

這個部落格


Syndication