当前元素在父级元素容器中,水平方向是居中显示的
<div id="box">水平文字居中</div>
#box {width: 200px;height: 200px;background: #c9394a;text-align: center;}
2.单个块级元素实现水平居中
<div id="parent"><div id="child">水平布局</div></div>
#parent {width: 100%;height: 200px;background: #ccc;}#child {width: 200px; /* 必须定宽 */height: 200px;background: #c9394a;margin: 0 auto;}
3.多个块级元素实现水平居中
块级元素改为行内块,换行、空格会产生间隔
<div id="parent"><div class="child1"></div><div class="child2"></div><!-- 手动去掉换行符即可 --></div>
#parent {width: 100%;height: 200px;background: #ccc;text-align: center; /* 父元素加 */}.child1 {width: 300px;height: 200px;background: #c9394a;display: inline-block; /* 子元素变为行内块 */}.child2 {width: 300px;height: 200px;background: green;display: inline-block;}
4.利用绝对定位水平居中
<div id="parent"><div id="child"></div></div>
#parent {width: 100%;height: 200px;background: #ccc;position: relative;}#child {width: 300px;height: 200px;background: #c9394a;position: absolute;left: 50%;/* margin-left: -150px; 自身宽度的一半 */transform: translateX(-50%);}
5.任意个元素(flex)
PC 端兼容性不好,一般用于移动端
<div id="parent"><div id="child"></div></div>
#parent {width: 100%;height: 200px;background: #ccc;display: flex; /* 加这两句即可 */justify-content: center;}#child {width: 300px;height: 200px;background: #c9394a;}
<div id="child">垂直居中</div>
#child {width: 200px;height: 200px;background: #c9394a;line-height: 200px;}
2.图片垂直居中
<div id="parent"><img src="./images/头像.png" alt="" /></div>
#parent {width: 400px;height: 600px;background: #ccc;line-height: 600px; /* 父级元素行高与高度相等 */}img {width: 200px;height: 200px;vertical-align: middle; /* 中线对齐;默认基线对齐 */}
3.利用绝对定位垂直居中
<div id="parent"><div id="child"></div></div>
#parent {width: 100%;height: 600px;background: #ccc;position: relative;}#child {width: 200px;height: 200px;background: #c9394a;position: absolute;top: 50%;/* margin-top: -100px; 自身高度的一半 */transform: translateY(-50%);}}
利用 table-cell
会导致父级元素的文本垂直居中
<div id="parent"><div id="child"></div></div>
#parent {width: 1000px;/* 必须给定一个具体的宽值,不然只能被子元素撑开 */height: 600px;background: #ccc;display: table-cell;vertical-align: middle; /* 垂直居中 */}#child {width: 200px;height: 200px;background: #c9394a;margin: 0 auto; /* 水平居中 */}
2.利用绝对定位
<div id="parent"><div id="child"></div></div>
#parent {position: relative;width: 100%;height: 600px;background: #ccc;}#child {position: absolute;top: 50%;left: 50%;width: 200px;height: 200px;background: #c9394a;/* margin-left: -100px; *//* margin-top: -100px; */transform: translate(-50%, -50%);}
3.利用 flex
PC 端兼容性不好,适用于移动端
<div id="parent"><div id="child"></div></div>
parent {width: 1000px;height: 600px;background: #ccc;display: flex;justify-content: center; /* 水平排列 */align-items: center; /* 垂直排列 */}#child {width: 200px;height: 200px;background: #c9394a;}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号