<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Several methods for CSS to achieve centering</title> </head> <body> <div class="parent"> <div class="child"></div> </div> <style> .parent{ width: 200px; height: 200px; background: #ccc; position: relative; /*1, flex layout implementation. Center justify-content horizontally, center align-items vertically*/ display:flex; justify-content: center; align-items: center; } .child{ width: 50px; height: 50px; background: #aaa; position: absolute; /*2, margin:auto implementation. Full center: auto, horizontal center: 0 auto, vertical center: auto 0*/ /*left:0; top: 0; bottom: 0; right: 0; margin: auto;*/ /*3, Transforms deformation implementation. The left and top values are the parent percentages, and the translate values are their own percentages*/ /*left: 50%; top: 50%; transform: translate(-50%,-50%);*/ /*4, the margin negative spacing is realized. The negative value of margin is -1/2*/ of width and height /*left: 50%; top: 50%; margin-left: -25px; margin-top: -25px;*/ } </style> </body> </html>