css如何居中一个div
2025-04-09
20
参考资料
水平居中
方法1: margin auto
div { width: 200px; margin: 0 auto; }
方法2: flexbox
.parent { display: flex; justify-content: center; }
垂直居中
方法1: flexbox
.parent { display: flex; align-items: center; height: 300px; }
方法2: transform
div { position: relative; top: 50%; transform: translateY(-50%); }
水平垂直居中
方法1: flexbox
.parent { display: flex; justify-content: center; align-items: center; height: 300px; }
方法2: absolute + transform
.parent { position: relative; height: 300px; } .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
完整示例:
<div class="parent"> <div class="child">居中内容</div> </div> <style> .parent { display: flex; justify-content: center; align-items: center; height: 300px; border: 1px solid #ccc; } .child { width: 200px; padding: 20px; background: #f0f0f0; } </style>
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。