1. 使用css3中的属性:transform: translate(x,y)
<style> .box { width: 100px; height: 100px; background: orange; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); } </style> </head> <body> <div class="box"></div> </body>
2.使用flex布局
<style> body { display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; padding: 0; } .box { width: 100px; height: 100px; background: orange; } </style> </head> <body> <div class="box"></div> </body>
3. 使用绝对定位,加上margin-left: -(width为盒子的一半), margin-top: -(height为盒子的一半)
<style> .box { width: 100px; height: 100px; background: orange; position: absolute; left: 50%; top: 50%; margin-left: -50px; margin-top: -50px; } </style> </head> <body> <div class="box"></div> </body>