1.代碼
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title></title> 6 <style> 7 *{ 8 margin: 0; 9 padding: 0; 10 } 11 12 div{ 13 /* width: 100px; 14 height: 100px; */ 15 background-color: #bfa; 16 position: absolute; 17 left: 50%; 18 top: 50%; 19 transform: translateX(-50%) translateY(-50%); 20 } 21 </style> 22 </head> 23 <body> 24 <div>dgjhio</div> 25 </body> 26 </html>
2.圖片
講解
1.不論對設置了寬高和沒有設置寬高的快元素,而且已經開啟了定位,相對包含塊元素定位,設置left: 50%;top:50%; 然后利用translateX(-50%) translateY(-50%); 移動自身的寬高各50%,
則該元素位於網頁正中央。