CSS的相對定位

來源:互聯網
上載者:User

標籤:style   io   color   ar   os   使用   sp   strong   div   

CSS的相對定位:

一.基本概念:
顧名思義,此種定位是相對某一個對象進行的位移,相對定位並不能使對象脫離文檔流,儘管它的位置可能產生位移,但是對象初始位置仍然會被保留。
如果要真正掌握此種定位方式,搞清楚需相對於哪個對象進行位移是關鍵點。
二.如何將一個元素設定為相對定位:
當一個對象的position屬性值被設定為relative的時候就會發生相對定位:

  position:relative

三.定位參考對象:
可以使用top屬性和left屬性設定相對定位對象的位移量。
相對定位的位移參考對象是此對象本身。
代碼執行個體:
首先看一個沒有使用定位的代碼執行個體:

<!DOCTYPE html> 
<html> 
<head> <meta charset=" utf-8"> 
<title>CSS相對定位</title>
<style type="text/css"> 
.father{ width:400px; height:400px; margin:50px; }
.first{ width:100px; height:100px; background-color:red }
.second{ width:100px; height:100px; background-color:blue }
</style> 
</head> 
<body> 
<div class="father"> 
<div class="first">
</div> 
<div class="second">
</div> 
</div> 
</body>
</html>

在以上代碼中,所有的對象都沒有採用相對定位,這裡無須多介紹了。
再來看一段採用相對定位的代碼:

<!DOCTYPE html> 
<html>
<head> <meta charset=" utf-8">
<title>CSS相對定位</title> 
<style type="text/css"> 
.father{ width:400px; height:400px; margin:50px; } 
.first{ width:100px; height:100px;
background-color:red; position:relative; left:20px; top:30px; } 
.second{ width:100px; height:100px; background-color:blue }
</style> 
</head>
<body> 
<div class="father">
<div class="first">
</div> 
<div class="second">
</div> 
</div>
</body>
</html>

在以上代碼中,first元素採用了相對定位,併產生位移,位移是以對象沒有產生位移前的位置為參考的。同時也可以看出,first元素的位移前的位置依然會被保留,它周邊的元素不能夠佔據。
特別說明:定位元素經常與z-index屬性一起使用,具體我們可以參閱CSS的z-index屬性用法詳解 

CSS的相對定位

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.