css中设置div居中
2025-04-09
17
参考资料
水平居中
行内元素
.parent { text-align: center; }块级元素(固定宽度)
.child { width: 200px; margin: 0 auto; }Flexbox
.parent { display: flex; justify-content: center; }Grid
.parent { display: grid; place-items: center; }
垂直居中
单行文本
.parent { height: 100px; line-height: 100px; }Flexbox
.parent { display: flex; align-items: center; }Grid
.parent { display: grid; place-items: center; }绝对定位(已知高度)
.child { position: absolute; top: 50%; height: 100px; margin-top: -50px; /* 高度的一半 */ }
水平垂直居中
Flexbox
.parent { display: flex; justify-content: center; align-items: center; }Grid
.parent { display: grid; place-items: center; }绝对定位 + transform
.child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
示例代码
<!DOCTYPE html>
<html>
<head>
<style>
/* 水平居中 */
.center-h {
width: 200px;
margin: 0 auto;
background: lightblue;
text-align: center;
}
/* 垂直居中 */
.container-v {
height: 200px;
display: flex;
align-items: center;
background: lightgray;
}
/* 水平垂直居中 */
.container-hv {
height: 300px;
display: grid;
place-items: center;
background: lightgreen;
}
.box-hv {
width: 150px;
height: 100px;
background: coral;
}
</style>
</head>
<body>
<div class="center-h">水平居中</div>
<div class="container-v">
<div>垂直居中</div>
</div>
<div class="container-hv">
<div class="box-hv">水平垂直居中</div>
</div>
</body>
</html>
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
本文来自《西里网 . html 网页设计》 -- 发布时间:2025-03-29
本页链接:https://html.ciilii.com/show/news-531.html
原创声明:本篇文章均为西里网原创,由《DeepSeek-R1 模型》自动生成。内容真实性仅供参考学习。
本作品采用 知识共享署名—非商业性使用—相同方式共享 4.0 国际许可协议 (CC BY-NC-SA 4.0) 进行许可。
