CSS实现水平垂直居中
目录
<body>
<div class="father">
<div class="son">
</div>
</div>
</body>
1.绝对定位加transform 不定宽高
.father{
position: relative;
background-color: antiquewhite;
}
.son{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
background-color: aqua;
}
2. margin负值
.father{
height: 200px;
width: 200px;
border: 1px solid rebeccapurple;
position: relative;
}
.son{
position: absolute;
height: 100px;
width: 100px;
left: 50%;
top: 50%;
margin-left: -50px;//width的一半
margin-top: -50px;//height的一半
background-color: aqua;
}
3.marign:auto
- 定位上下左右为0,margin:0可以实现脱离文本流的居中
.father{
height: 200px;
width: 200px;
border: 1px solid rebeccapurple;
position: relative;
}
.son{
position: absolute;
height: 100px;
width: 100px;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
background-color: aqua;
}
4. flex布局
父元素设置: display: flex;
justify-content: center;
align-items: center;
.father{
height: 200px;
width: 200px;
border: 1px solid rebeccapurple;
display: flex;
justify-content: center;对齐子项目的水平中心
align-items: center;//垂直布局 align-items
}
.son{
height: 100px;
width: 100px;
background-color: aqua;
}
5. grid布局
.father{
height: 200px;
width: 200px;
border: 1px solid rebeccapurple;
display: grid;
margin: 0 auto;
}
.son{
height: 100px;
width: 100px;
background-color: aqua;
justify-self: center;
align-self: center;
}
6.table-cell
.father{
height: 200px;
width: 200px;
border: 1px solid rebeccapurple;
display: table-cell;
text-align: center;
vertical-align: middle//里面的内容会垂直居中
}
.son{
height: 100px;
width: 100px;
background-color: aqua;
margin: auto;
}