- 盒子水平居中:
margin: 0 auto;
使用条件:设置了指定宽度的块级元素
- 单行文本水平居中
text-align:center;
- 文字垂直居中
单行文本用 line-height
多行文本可以用 padding
常用垂直水平居中的方法
<body>
<div class="fa">
<div class="son">
</div>
</div>
</body>
1. 使用弹性盒子居中,为父元素设置如下代码
.fa{
width: 400px;
height: 400px;
background-color: aquamarine;
display: flex;
justify-content: center;
align-items: center;
}
2. 使用绝对定位,父元素设置为相对定位,子元素绝对定位,子元素关键样式代码如下
方法一:
.son{
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
方法二:
.son{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}