实现水平垂直居中的几种方式
基本页面代码
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| <!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> *{ padding: 0; margin: 0; } .parent { width: 500px; height: 500px; border: 5px solid black; margin: 50px auto; position: relative; } .parent-text { position: absolute; left: 0; bottom: 0; } .child { width: 100px; height: 100px; background-color:blueviolet; } </style> </head> <body> <div class="parent"> <div class="parent-text">我是父元素</div> <div class="child"> <div>我是子元素</div> </div> </div> </body> </html>
|
页面示意图:

Mode One Flex 布局
flex 布局的方式需要将父元素变为 flex 布局,再设置父元素的垂直居中和水平居中。
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| *{ padding: 0; margin: 0; } .parent { width: 500px; height: 500px; border: 5px solid black; margin: 50px auto; position: relative; display: flex; justify-content: center; align-items: center; } .parent-text { position: absolute; left: 0; bottom: 0; } .child { width: 100px; height: 100px; background-color:blueviolet; }
|
效果图:

Mode Two 绝对定位
绝对定位主要利用定位和平移实现元素的水平垂直居中
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| *{ padding: 0; margin: 0; } .parent { width: 500px; height: 500px; border: 5px solid black; margin: 50px auto; position: relative; } .parent-text { position: absolute; left: 0; bottom: 0; } .child { width: 100px; height: 100px; background-color:blueviolet; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
|
效果图:

注意:使用此方法一定要父元素相对定位