css div居中对齐方式
2025-04-09
18
参考资料
CSS Div居中对齐方式
水平居中
使用margin: auto
.center-div { width: 200px; margin: 0 auto; }
使用flexbox
.parent { display: flex; justify-content: center; }
使用grid
.parent { display: grid; place-items: center; }
使用text-align (内联元素)
.parent { text-align: center; }
垂直居中
使用flexbox
.parent { display: flex; align-items: center; height: 300px; /* 需要指定高度 */ }
使用grid
.parent { display: grid; place-items: center; height: 300px; }
使用绝对定位和transform
.center-div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
使用line-height (单行文本)
.center-div { line-height: 300px; /* 等于容器高度 */ height: 300px; }
水平和垂直同时居中
flexbox方法
.parent { display: flex; justify-content: center; align-items: center; height: 300px; }
grid方法
.parent { display: grid; place-items: center; height: 300px; }
绝对定位方法
.parent { position: relative; height: 300px; } .center-div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
示例
<!DOCTYPE html> <html> <head> <style> .flex-center { display: flex; justify-content: center; align-items: center; height: 200px; border: 1px solid #000; } .grid-center { display: grid; place-items: center; height: 200px; border: 1px solid #000; margin-top: 20px; } .transform-center { position: relative; height: 200px; border: 1px solid #000; margin-top: 20px; } .transform-center div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: #f0f0f0; padding: 10px; } </style> </head> <body> <div class="flex-center"> <div>Flexbox居中</div> </div> <div class="grid-center"> <div>Grid居中</div> </div> <div class="transform-center"> <div>Transform居中</div> </div> </body> </html>
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。