让一个行内元素(文字、图片等)水平垂直居中
操作简单,只需要父容器设置
.father {
height: 50px;
line-height: 50px;//垂直居中 行高=高
text-align: center;//水平居中
}
运行结果:
让一个块级元素水平垂直居中
- 方法1:绝对定位 + translate //不需要设置父元素
.son{ position: absolute;
background: red;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);}
- 方法2:父容器设置flex 布局(待改进)
.father{
display: flex;
justify-content: center;/*水平居中*/
align-items: center;/*垂直居中*/
}
- 方法3: 父容器设置flex 布局 + 子容器设置margin: auto (推荐)能解决大多时候情况
.father{
display: flex;
min-height: 100vh; //=height:100%;
}
.son {
margin: auto;
}
- 方法4:display: table-cell 实现水平垂直居中 针对子容器
css样式
.father {
display: table-cell;
vertical-align: middle;
width: 200px;
height: 200px;
background-color: skyblue;
}
.son {
width: 50%;
margin: 0 auto;
background-color: slateblue;
}
html代码
<div class="father">父元素
<div class="son">子元素
</div>
</div>
运行结果
- 方法5:父元素相对定位,子元素绝对定位。
.father{
position: relative;
width: 300px;
height: 300px;
background-color: skyblue;
}
.son{
width: 100px;
height: 100px;
position: absolute;
margin: auto;
top: 0; left: 0; bottom: 0; right: 0;
background-color: lightcoral;
}
<div class="father">
父元素的相对定位
<div class="son">
子元素的绝对定位
</div>
运行结果
-
方法6:设置外边距:margin-left:值; margin-top:值;
需要加入自身div的宽高计算,内容可能溢出容器(不推荐) -
方法7:用calc计算