如何垂直居中一个元素?img 呢?
方法一:绝对定位居中(已知元素的高宽)
.content {
width: 200px;
height: 200px;
background-color: #6699ff;
position: absolute;
/* 父元素需要相对定位 */
top: 50%;
left: 50%;
margin-top: -100px; /* 设为高度的 1/2 */
margin-left: -100px; /* 设为宽度的 1/2 */
}
方法二:绝对定位 + transform(未知元素的高宽)
.content {
width: 200px;
height: 200px;
background-color: #6699ff;
position: absolute;
/* 父元素需要相对定位 */
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* 在水平和垂直方向上各偏移 -50% */
}
方法三:绝对定位 + margin: auto
.content {
width: 200px;
height: 200px;
background-color: #6699ff;
margin: auto;
position: absolute;
/* 父元素需要相对定位 */
left: 0;
top: 0;
right: 0;
bottom: 0;
/* 让四个定位属性都为 0 */
}
方法四:flex 布局居中(推荐)
.parent {
display: flex;
/* 设置外层盒子 display 为 flex */
align-items: center; /* 设置内层盒子的垂直居中 */
justify-content: center; /* 设置内层盒子的水平居中 */
}
.content {
width: 200px;
height: 200px;
background-color: #6699ff;
}
垂直居中一个 img 的更简便方法
.img-wrap {
/* img 的容器设置如下 */
display: table-cell;
text-align: center;
vertical-align: middle;
}
补充:
- 单行文本垂直居中:
line-height = height;多行文本垂直居中:display: table-cell; vertical-align: middle;。- 现代最推荐的方案是 flex / grid:
display: flex; align-items: center; justify-content: center;一行解决。- 想让一个不知道尺寸的 img 居中,可以让父容器
display: flex; place-items: center;或display: grid; place-items: center;。



