方法1:利用css的 position属性
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> *{ margin: 0; padding: 0; } .father{ width: 300px; height: 300px; background-color: salmon; position: relative; } .child{ position: absolute; width: 100px; height: 100px; background-color: rgb(146, 226, 226); top: 50%; left: 50%; margin-top: -50px; margin-left:-50px; } </style> </head> <body> <div class="father"> <div class="child"></div> </div> </body> </html>
效果如图:
方法二:利用css的 position属性
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> *{ margin: 0; padding: 0; } .father{ width: 300px; height: 300px; background-color: salmon; position: relative; } .child{ position: absolute; width: 100px; height: 100px; left: 0; top: 0; right: 0; bottom: 0; margin: auto; background-color: rgb(146, 226, 226); } </style> </head> <body> <div class="father"> <div class="child"></div> </div> </body> </html>
效果如图: