HTML&CSS基礎-元素的層級
作者:尹正傑
版權聲明:原創作品,謝絕轉載!否則將追究法律責任。
一.HTML源代碼
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>元素的層級</title> <style type="text/css"> .box1{ width: 200px; height: 200px; background-color: red; position: relative; z-index: 2; } .box2{ width: 200px; height: 200px; background-color: yellow; /*開啟絕對定位*/ position: absolute; /*設置偏移量*/ top: 100px; left: 100px; /* * 如果定位元素的層級是一樣,則下邊的元素會蓋住上邊的,通過z-index屬性可以用來設置元素的層級 * * 可以為z-index指定一個正整數的值,該值將會作為當前元素的層級,層級越高,越優先顯示 * * 對於沒有開啟定位的元素不能使用z-index */ z-index: 25; } .box3{ width: 200px; height: 200px; background-color: yellowgreen; } .box4{ width: 200px; height: 200px; background-color: orange; /*開啟相對定位*/ position: relative; /* * 父元素的層級再高,也不會蓋住子元素 */ z-index: 20; } .box5{ width: 100px; height: 100px; background-color: skyblue; /*開啟絕對定位*/ position: absolute; z-index: 10; } </style> </head> <body style="height: 5000px;"> <div class="box1"></div> <div class="box2"></div> <div class="box3"></div> <div class="box4"> <div class="box5"></div> </div> </body> </html>
二.瀏覽器打開以上代碼渲染結果