方法一: display:flex
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="../css_com/reset.css"> <style> .parents{ /*添加部分*/ display: flex; align-items: center; justify-content: center; margin:0 auto; width: 600px; height: 600px; background-color: #4eff5e; } .son{ width: 300px; height: 300px; background-color: #ff4236; } </style> </head> <body> <div class="parents"> <div class="son"></div> </div> </body> </html>
方法二:display:table-cel
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="../css_com/reset.css"> <style> .parents{ /*添加部分*/ display: table-cell; vertical-align: middle; margin:0 auto; width: 600px; height: 600px; background-color: #4eff5e; } .son{ /*添加部分*/ margin: auto; width: 300px; height: 300px; background-color: #ff4236; } </style> </head> <body> <div class="parents"> <div class="son"></div> </div> </body> </html>
方法三:绝对定位和0
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="../css_com/reset.css"> <style> .parents{ /*添加部分*/ position: relative; margin:0 auto; width: 600px; height: 600px; background-color: #4eff5e; } .son{ /*添加部分*/ margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; width: 300px; height: 300px; background-color: #ff4236; } </style> </head> <body> <div class="parents"> <div class="son"></div> </div> </body> </html>
方法四:负边距
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="../css_com/reset.css"> <style> .parents{ /*添加部分*/ position: relative; margin:0 auto; width: 600px; height: 600px; background-color: #4eff5e; } .son{ /*添加部分*/ position: absolute; top: 50%; left: 50%; margin-left: -150px; margin-top: -150px; width: 300px; height: 300px; background-color: #ff4236; } </style> </head> <body> <div class="parents"> <div class="son"></div> </div> </body> </html>
方法四:css3属性中的平移
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="../css_com/reset.css"> <style> .parents{ /*添加部分*/ position: relative; margin:0 auto; width: 600px; height: 600px; background-color: #4eff5e; } .son{ /*添加部分*/ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); width: 300px; height: 300px; background-color: #ff4236; } </style> </head> <body> <div class="parents"> <div class="son"></div> </div> </body> </html>
目前总结这四种方法,实际使用的时候根据实际情况选取不同的方法