#轉載請先留言聯系
-
定位
HTML中的position屬性可以對元素進行定位,通過position的不同的值,可以配合方位屬性,讓元素顯示頁面中的任何一個位置。
position有四個值:
static,默認值,去除元素的定位。也就是不進行定位
relative,相對定位,元素相對於自身原來的位置進行定位。
absolute,絕對定位,元素相對於當前父元素進行定位。
fixed,固定定位,元素相對於瀏覽器頁面窗口進行定位。
怎么定位?css中提供了四個不同方位屬性給我們進行定位。
top:表示距離頂部指定的長度
bottom:表示距離底部指定的長度
left:表示距離左邊指定的長度
right:表示距離右邊指定的長度
示例:
1.relative定位
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .box{ width:200px; height: 200px; background: #000; position: relative; /*讓元素相對於自身原有的位置進行定位*/ top:100px; /*向下移動100px*/ left: 100px; /*向左移動100px*/ /*定位中,left與right,top與bottom一般不同時使用*/ } </style> </head> <body> <div class="box"></div> </body> </html>;
2.absolute定位
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .box{ width: 500px; height: 500px; background: blue; position: absolute; top: 100px; left: 100px; } .son{ width: 100px; height: 100px; background: black; position: absolute; top: 200px; left: 200px; } </style> </head> <body> <div class="box"> <div class="son"></div> </div> </body> </html>
absolute定位有一個很常用的用途,就是當希望子元素在父元素的正中央時,可以這樣操作:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .box{ width: 500px; height: 500px; background: blue; position: absolute; top: 100px; left: 100px; } .son{ width: 100px; height: 100px; background: black; position: absolute; left: 0; /* 注意不要漏了上下左右為0,否則不會成功 */ right: 0; top: 0; bottom: 0; margin: auto; } </style> </head> <body> <div class="box"> <div class="son"></div> </div> </body> </html>
3.fixed定位
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .one{ width: 100px; height: 300px; background: blue; position: fixed; right: 0; top: 300px; } .two{ width: 100px; height: 300px; background: blue; position: fixed; left: 0; top: 300px; } </style> </head> <body> <div class="one"></div> <div class="two"></div> </body> </html>
設置了定位后可以設置層級。
-
層級
通過z-index進行設置,所有的元素的z-index默認值為0,我們可以通過z-index,設置不同的值來控制定位元素之間的覆蓋。值越大的,層級越高,值越小,層級就越低,如果定位元素的層級為-1,則會被普通沒有定位的元素進行覆蓋。
示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .one{ width: 100px; height: 200px; background: red; position: absolute; } .two{ width: 100px; height: 100px; background: yellow; position: absolute; z-index: 1; } .three{ width: 100px; height: 300px; background: blue; position: absolute; z-index: -2; } </style> </head> <body> <div class="one"></div> <div class="two"></div> <div class="three"></div> </body> </html>