1.使用相对定位和绝对定位
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .box{ width: 400px; height: 200px; margin: 50px auto; background-color: #E3E1E2; position: relative; } .item{ width: 80px; height: 80px; background-color: #D2388F; position: absolute; left: 50%; top: 50%; margin-left: -40px; margin-top: -40px; } </style> </head> <body> <div class="box"> <div class="item"></div> </div> </body> </html>效果图如下:
2.使用flex布局
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .box{ width: 400px; height: 200px; margin: 100px auto; background-color: #E3E1E2; display: flex; justify-content: center; align-items: center; } .item{ width: 80px; height: 80px; background-color: #D2388F; } </style> </head> <body> <div class="box"> <div class="item"></div> </div> </body> </html>效果图和方法1的效果图是一样的,此处就不截图了
比较上述方法可以发现,使用flex布局比绝对,相对定位要简单一些