实现元素的水平垂直居中(宽高已知):
- 单行文本居中
水平居中:text-align:center;垂直居中:line-height:XXpx; /*line-height与元素的height的值一致*/
2.多行文本居中
display:table
主要实现代码:
display: table使块状元素成为一个块级表格;
display: table-cell;子元素设置成表格单元格;
vertical-align: middle;使表格内容居中显示,即可实现垂直居中的效果;
.box {
width: 300px;
height: 300px;
margin: 0 auto;
display: table;
background: #ff5576;
}
.box p {
color: #fff;
display: table-cell;
vertical-align: middle;
}
<div class="box">
<p>
宽高父元素为300px背景颜色是红色 元素内字体为白色 父元素box设置为display:table 子元素p便签设置为display:table-cell
</p>
</div>
3.使用相对定位、绝对定位
父元素设置宽高position relative,子元素设置绝对定位position absolute top和left位移本身宽高的一半
(transform:translate(-50%,-50%)))
具体代码实现:
<div class="box2">
<div class="ch2">
</div>
</div>
.box2{
width: 300px;
height: 300px;
background: #0076ff;
position: relative;
}
.ch2{
width: 100px;
height: 100px;
position: absolute;
background: #ff5577;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
4、使用display:flex将父元素设置为弹性盒,再给子元素设置 align-items: center;定义项目在交叉轴(纵轴)上如何对齐,垂直对齐居中
justify-content: center; 定义了项目在主轴上的对齐方式,水平对齐居中
#box{
width: 400px;
height: 400px;
background: red;
display: flex;
justify-content: center;
align-items: center;
}
#x{
width: 200px;
height: 200px;
background: yellow;
}
5.父元素设置相对定位 子元素自适应
#box{
width: 400px;
height: 400px;
background: red;
position: relative;
}
#x{
width: 200px;
height: 200px;
background: yellow;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
宽高未知(4种方案):
方案1:定位
html
<div class="father">
<div class="son"></div>
</div>
css
.father {
position: relative;
width: 200px;
height: 200px;
background: skyblue;
}
.son {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 100px;
height: 100px;
background: red;
}
方案2:flex
html不变:
<div class="father">
<div class="son"></div>
</div>
css
.father {
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
background: skyblue;
}
.son {
width: 100px;
height: 100px;
background: red;
}
方案3:table布局
需要设置父元素为display:table-cell,利用vertical和text-align可以让所有的行内块级元素水平垂直居中
给子元素设置 display: inline-block
html不变:
<div class="father">
<div class="son"></div>
</div>
css:
.father {
display: table-cell;
width: 200px;
height: 200px;
background: skyblue;
vertical-align: middle;
text-align: center;
}
.son {
display: inline-block;
width: 100px;
height: 100px;
background: red;
}
方案4:grid布局
html不变
<div class="father">
<div class="son"></div>
</div>
css不变:
.father {
display: grid;
align-items:center;
justify-content: center;
width: 200px;
height: 200px;
background: skyblue;
}
.son {
width: 10px;
height: 10px;
border: 1px solid red
}