css div居中代码
2025-04-09
30
参考资料
css div居中代码
水平居中:
div { margin: 0 auto; width: 200px; }
水平垂直居中(flex布局):
.container { display: flex; justify-content: center; align-items: center; height: 100vh; }
水平垂直居中(绝对定位):
div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
水平垂直居中(grid布局):
.container { display: grid; place-items: center; height: 100vh; }
完整示例(flex方案):
<!DOCTYPE html> <html> <head> <style> .container { display: flex; justify-content: center; align-items: center; height: 100vh; border: 1px solid #ccc; } .box { width: 200px; height: 100px; background: #f0f0f0; text-align: center; line-height: 100px; } </style> </head> <body> <div class="container"> <div class="box">居中内容</div> </div> </body> </html>