CSS实现盒子水平垂直居中的方法
CSS实现盒子水平垂直居中的方法
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <title>Document</title> 8 </head> 9 <body> 10 <div> 11 <p></p> 12 </div> 13 </body> 14 </html>
1:利用子绝父相定位的方式来实现
1 <style> 2 div { 3 position: relative; 4 width: 200px; 5 height: 200px; 6 background-color:pink; 7 8 } 9 10 p { 11 position: absolute; 12 top: 50%; 13 left: 50%; 14 width: 100px; 15 height: 100px; 16 margin-top: -50px; 17 margin-left: -50px; 18 background-color:skyblue; 19 } 20 </style>
2:利用CSS3的transform,可以轻松的在未知元素的高宽的情况下实现元素的垂直居中
1 <style> 2 div { 3 position: relative; 4 width: 200px; 5 height: 200px; 6 background-color:pink; 7 8 } 9 10 11 p { 12 position: absolute; 13 top: 50%; 14 left: 50%; 15 width: 100px; 16 height: 100px; 17 transform: translate(-50%, -50%); 18 background-color:skyblue; 19 } 20 </style>
3:利用flex来实现
1 <style> 2 div { 3 width: 200px; 4 height: 200px; 5 pink; 6 display: flex; 7 justify-content: center; 8 align-items: center; 9 } 10 11 p { 12 width: 100px; 13 height: 100px; 14 background-color:skyblue; 15 } 16 </style>

浙公网安备 33010602011771号