關於CSS中的position:relative;的作用介紹

來源:互聯網
上載者:User
這篇文章主要介紹了關於CSS中的position:relative;的作用介紹,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

CSS中的position:relative是控制元素相對定位的,relative 不脫離文檔流而absolute 脫離文檔流,relative 的元素儘管表面上看到它偏離了原來的位置,但它實際上在文檔流中還是沒變

引用

static :  無特殊定位,對象遵循HTML定位規則
absolute :  將對象從文檔流中拖出,使用left,right,top,bottom等屬性進行絕對位置。而其層疊通過z-index屬性定義。此時對象不具有邊距,但仍有補白和邊框
relative :  對象不可層疊,但將依據left,right,top,bottom等屬性在正常文檔流中位移位置
fixed :  IE5.5及NS6尚不支援此屬性

"對於頁面中一個static的p#demo,我想讓這個#demo裡的一個p#sub相對於#demo定位在右上方的某個地方,應該是用這個position:relative這個吧,然後再加上top,right給限制一下。
我理解得沒有錯吧? "
首先對你疑惑的地方,我先解答一下:
position的預設值是static,(也就是說對於任意一個元素,如果沒有定義它的position屬性,那麼它的position:static)
如果你想讓這個#demo裡的一個p#sub相對於#demo定位在右上方的某個地方,應該給#demo相對定位,#sub絕對位置。
absolute是相對於自己最近的父元素來定位的,如果你不給#demo相對定位,那麼#sub的絕對位置就是相對於body來定位的。
relative是相對於自己來定位的,例如:#demo{position:relative;top:-50px;},這時#demo會在相對於它原來的位置上移50px。
另:relative 不脫離文檔流,absolute 脫離文檔流。也就是說:relative 的元素儘管表面上看到它偏離了原來的位置,但它實際上在文檔流中還是沒變。absolute的元素不僅位置改變了,同時也脫離了文檔流。

寫了個例子如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>position</title> <style type="text/css"> <!-- body{ font-size:12px; margin:0 auto; } p#demo{ position:relative; border:1px solid #000; margin:50px; top:-50px; line-height:18px; overflow:hidden; clear:both; height:1%; } p#sub{ position:absolute; right:10px; top:10px; } p.relative{ position:relative; left:400px; top:-20px; } p.static,p.fixed,p.absolute,p.relative{ width:300px; } p.static{ background-color:#bbb; position:static; } p.fixed{ background-color:#ffc0cb; } p.absolute{ background-color:#b0c4de; } p.relative{ background-color:#ffe4e1; } --> </style> </head> <body> <p id="demo"> <p class="static">static: 預設值。無特殊定位,對象遵循HTML定位規則 </p> <p id="sub" class="absolute">absolute: 將對象從文檔流中拖出,使用left,right,top,bottom 等屬性相對於其最接近的一個最有定位設定的父物件進行絕對位置。如果不存在這樣的父物件,則依據body對象。而其層疊通過z-index屬性定義 </p> <p class="fixed">fixed:未支援。對象定位遵從絕對(absolute)方式。但是要遵守一些規範 </p> <p class="relative">relative:對象不可層疊,但將依據 left,right,top,bottom 等屬性在正常文檔流中位移位置 </p> </p> </body> </html>

以上就是本文的全部內容,希望對大家的學習有所協助,更多相關內容請關注topic.alibabacloud.com!

相關文章

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.