代码:
<!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> .father{ position: relative; width: 500px; height: 300px; border: 2px black solid; margin: 200px auto; } /* 之前定位的写法 当子元素宽高变化时 子元素就不居中了 因为margin-left和-top 写死了 */ /* .son{ position: absolute; width: 200px; height: 100px; top: 50%; left: 50%; margin-left: -100px; margin-top: -50px; background-color: pink; } */ /* 优化 */ /* 垂直水平居中的终极版本 */ .son{ position: absolute; width: 200px; height: 100px; top: 50%; left: 50%; transform: translate(-50%,-50%); background-color: pink; } </style> </head> <body> <div class="father"> <div class="son"></div> </div> </body> </html>
效果图: