css 居中的汇总
前言
对css居中的几种方式汇总,并且分析适用情况。
正文
margin+position
.CenterParent {
position: relative;
height: 200px;
width: 200px;
background-color:yellow;
}
.CenterChild{
position:absolute;
height: 100px;
width: 100px;
top:50%;
left: 50%;
margin-top:-50px;
margin-left:-50px;
background-color: red;
}
<div class="CenterParent">
<div class="CenterChild">
</div>
</div>
后续不展示效果。
优点:兼容全部浏览器
缺点:需要知道子元素的宽高。
margin:aotu+postion
.CenterParent {
position: relative;
height: 200px;
width: 200px;
background-color:yellow;
}
.CenterChild{
position:absolute;
height: 100px;
width: 100px;
top:0px;
left: 0px;
bottom: 0px;
right: 0px;
margin: auto;
background-color: red;
}
中规中距:需要兼容的推荐。
flex
.CenterParent {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
width: 200px;
background-color:yellow;
}
.CenterChild{
height: 100px;
width: 100px;
background-color: red;
}
缺点:需要浏览器支持flex
margin+transtion
.CenterParent {
position: relative;
height: 200px;
width: 200px;
background-color:yellow;
}
.CenterChild{
position: absolute;
top: 50%;
left: 50%;
transform:translate( -50%, -50%);
height: 100px;
width: 100px;
background-color: red;
}
缺点:需要支持transform
table-cell
.CenterParent {
display: table-cell;
text-align: center;
vertical-align: middle;
height: 200px;
width: 200px;
background-color:yellow;
}
.CenterChild{
width: 100px;
height: 100px;
display: inline-block;
background-color: red;
}
子元素必须是:inline-block或者inline.