使用position屬性對DIV進行布局

來源:互聯網
上載者:User
相對定位和絕對位置

定位標籤:position
包含屬性:relative(相對) absolute(絕對)
1.position:relative; 如果對一個元素進行相對定位,首先它將出現在它所在的位置上。然後通過設定垂直或水平位置,讓這個元素"相對於"它的原始起點進行移動。(再一點,相對定位時,無論是否進行移動,元素仍然佔據原來的空間。因此,移動元素會導致它覆蓋其他框)

2.position:absolute; 表示絕對位置,位置將依據瀏覽器左上方開始計算。 絕對位置使元素脫離文檔流,因此不佔據空間。普通文檔流中元素的布局就像絕對位置的元素不存在時一樣。(因為絕對位置的框與文檔流無關,所以它們可以覆蓋頁面上的其他元素並可以通過z-index來控制它層級次序。z-index的值越高,它顯示的越在上層。)

3.父容器使用相對定位,子項目使用絕對位置後,這樣子項目的位置不再相對於瀏覽器左上方,而是相對於父視窗左上方

4.相對定位和絕對位置需要配合top、right、bottom、left使用來定位具體位置,這四個屬性只有在該元素使用定位後才生效,其它情況下無效。另外這四個屬性同時只能使用相鄰的兩個,不能即使用上又使用下,或即使用左,又使用右。

下面是一個p內多個p的相對絕對布局:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>  <head>    <title>testp.html</title>        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3" />    <meta http-equiv="description" content="this is my page"/>    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>        <script type="text/javascript">        window.onload = function(){            document.getElementById("myp").style.height = "200px";        };    </script>  </head>    <body>      關鍵因素:外層加position:relative,裡面的p使用position: absolute,<br />      但這種方法的問題有:外層的p必須指定具體的height,高度不能使用百分比   <!--  <p style="position:relative;width: 600px;height:500px;">        <p style="width: 100px;height: 50px; position: absolute;right:10px;bottom: 10px"></p>    </p> -->         <p id="myp" style="position:relative;width: 100%;height:auto;">        <p style="width: 100px;height: 50px; position: absolute;right:10px;bottom: 10px"></p>        <p style="width: 100px;height: 50px; position: absolute;left:10px;bottom: 10px"></p>    </p>  </body></html>


相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.