1、flex布局
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 7 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 <title>Document</title> 9 <style> 10 /* display flex */ 11 .outer { 12 width: 500px; 13 height: 500px; 14 background-color: pink; 15 margin: 0 auto; 16 display: flex; 17 justify-content: center; 18 align-items: center; 19 } 20 .outer .inner { 21 width: 200px; 22 height: 200px; 23 background-color: aqua; 24 } 25 </style> 26 </head> 27 28 <body> 29 <div class="outer"> 30 <div class="inner"></div> 31 </div> 32 </body> 33 34 </html>
2、absolute + 负margiin
适用于元素宽高已知的情况
原理:设置元素的绝对定位,让元素以屏幕左上角定位,设置top:50%;left:50%;距屏幕上和左各一半,此时显示如下:

只需要将元素的上外边距和左外边距移动自身宽度的一半即可实现水平垂直居中。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> div{ width: 200px; height: 200px; background-color: red; position: absolute; top:50%; left: 50%; margin-top: -100px; margin-left: -100px; } </style> </head> <body> <div></div> </body> </html>
3、absolute + transform
适用于元素宽高未知的情况
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title></title> <style type="text/css"> .outer{ width: 500px; height: 500px; background-color: pink; margin: 0 auto; position: relative; } .inner{ width: 200px; height: 200px; background-color: aqua; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); } </style> </head> <body> <div class="outer"> <div class="inner"></div> </div> </body> </html>
4、display:table-cell
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .outer { width: 500px; height: 500px; background-color: pink; display: table-cell; vertical-align: middle; } .inner { width: 200px; height: 200px; background-color: aqua; margin: 0 auto; } </style> </head> <body> <div class="outer"> <div class="inner"> </div> </div> </body> </html>
5、position:absolute + margin:auto
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .outer{ width: 500px; height: 500px; background-color: pink; margin: 50px auto; position: relative; } .inner{ width: 200px; height: 200px; background-color: red; position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; } </style> </head> <body> <div class="outer"> <div class="inner"></div> </div> </body> </html>
浙公网安备 33010602011771号