本篇文章給大家?guī)砹岁P(guān)于css的相關(guān)知識,其中主要介紹了關(guān)于CSS定位屬性中relative相對定位的相關(guān)問題,相對定位是元素在移動位置的時候,是相對于它原來的位置來說的,設(shè)置為相對定位的元素框會偏移某個距離,下面一起來看一下,希望對大家有幫助。
(學習視頻分享:css視頻教程、html視頻教程)
CSS定位屬性之相對定位relative屬性詳解
position:relative 相對定位詳解
相對定位是元素在移動位置的時候,是相對于它原來的位置來說的。
相對定位的特點:
-
它是相對于自己原來的位置來移動的(移動位置的時候參考點是自己原來的位置)
-
原來在標準流的位置繼續(xù)占有,后面的盒子仍然以標準流的方對待它(不脫標,繼續(xù)保留原來的位置)。因此相對定位并沒有脫標,它最典型的應用是給絕對定位當?shù)摹?/p>
設(shè)置為相對定位的元素框會偏移某個距離。元素仍然保持其未定位前的形狀,它原本所占的空間仍保留。
CSS 相對定位
相對定位是一個非常容易掌握的概念。如果對一個元素進行相對定位,它將出現(xiàn)在它所在的位置上。然后,可以通過設(shè)置垂直或水平位置,讓這個元素“相對于”它的起點進行移動。
如果將 top 設(shè)置為 20px,那么框?qū)⒃谠恢庙敳肯旅?20 像素的地方。如果 left 設(shè)置為 30 像素,那么會在元素左邊創(chuàng)建 30 像素的空間,也就是將元素向右移動。
#box_relative { position: relative; left: 30px; top: 20px; }
如下圖所示:
注意,在使用相對定位時,無論是否進行移動,元素仍然占據(jù)原來的空間。因此,移動元素會導致它覆蓋其它框。
示例如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <style type="text/css"> body{ margin:10px; font-size:12px; font-family:Arial; } .outside{ width:1000px; height:600px; background-color:#a9d6ff; border:1px dashed black; } .inside{ padding:10px; background-color:#fffcd3; border:1px dashed black; margin: 10px; } .inside1{ margin:10px; padding: 10px; background-color:#fffcd3; border:1px dashed black; /* 設(shè)置相對定位 ,相對點是當前div的原始位置的左上角*/ position: relative; /* 距離div的原始位置的左邊框 */ left:20px; /* 距離div的原始位置的上邊框 */ top:30px; /* right距離div的原始位置的右邊框 bottom距離div的原始位置的下邊框 */ } </style> </head> <body> <div class="outside"> <div class="inside">div1</div> <div class="inside1">div2</div> </div> </body> </html>
輸出結(jié)果:
相對定位對文檔流的影響
代碼示例:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <style type="text/css"> body{ margin:10px; font-size:12px; font-family:Arial; } .outside{ width:1000px; height:600px; background-color:#a9d6ff; border:1px dashed black; } .inside{ padding:10px; background-color:#fffcd3; border:1px dashed black; margin: 10px; position:relative; left:30px; top:30px; /* div1相對定位脫離了文檔流, 但是后續(xù)的div還會認為div1是在沒有相對定位之前的狀態(tài) 所有后續(xù)的div不會填補div1的空缺位置,而是繼續(xù)按照文檔流來排序 */ } .inside1{ margin:10px; padding: 10px; background-color:#fffcd3; border:1px dashed black; } </style> </head> <body> <div class="outside"> <div class="inside">div1</div> <div class="inside1">div2</div> </div> </body> </html>
輸出結(jié)果:
(學習視頻分享:css視頻教程、html視頻教程)