css样式div居中
2025-04-09
17
参考资料
CSS居中方法
水平居中
div { margin: 0 auto; width: 200px; }
Flexbox居中
.container { display: flex; justify-content: center; /* 水平居中 */ align-items: center; /* 垂直居中 */ height: 100vh; }
Grid居中
.container { display: grid; place-items: center; height: 100vh; }
绝对定位居中
div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
完整示例
<!DOCTYPE html> <html> <head> <style> .center-div { width: 200px; height: 100px; background: #ccc; /* 方法1 */ margin: 0 auto; /* 方法2 */ display: flex; justify-content: center; align-items: center; /* 方法3 */ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } </style> </head> <body> <div class="center-div">居中内容</div> </body> </html>
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。