前言
对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.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。