如何让子元素在父元素中水平垂直居中七种方法?

44次阅读

共计 1523 个字符,预计需要花费 4 分钟才能阅读完成。

html:
<div class=”container”>
<div class=”box”>green</div>
</div>
第一种:定位 +margin:auto
.container {
position: relative;
width: 300px;
height: 300px;
background: yellow;
}
.box {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
width: 100px;
height: 100px;
background: red;
}
注意:兼容性较好,缺点: 不支持 IE7 以下的浏览器第二种:定位 +margin-left+margin-top
.container {
position: relative;
width: 300px;
height: 300px;
background: yellow;
}
.box {
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
width: 100px;
height: 100px;
background: red;
}
注意:兼容性好; 缺点: 必须知道元素的宽高第三种:定位 +transfrom
.container {
position: relative;
width: 300px;
height: 300px;
background: yellow;
}
.box {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
width: 100px;
height: 100px;
background: red;
}
注意:这是 css3 里的样式; 缺点: 兼容性不好,只支持 IE9+ 的浏览器第四种:弹性盒子
.container {
display: flex;
justify-content: center;
align-items: center;
width: 300px;
height: 300px;
background: yellow;
}
.box {
width: 100px;
height: 100px;
background: red;
}
移动端首选第五种:flex+margin: auto
.container {
display: flex;
width: 300px;
height: 300px;
background: yellow;
}
.box {
margin: auto;
width: 100px;
height: 100px;
background: red;
}
移动端首选第六种:形成 table-cell, 子元素设置 display:inline-block
.container {
display: table-cell;
vertical-align: middle;
text-align: center;
width: 300px;
height: 300px;
background: yellow;
}
.box {
display: inline-block;
width: 100px;
height: 100px;
background: red;
}
注意:兼容性:由于 display:table-cell 的原因,IE67 不兼容第七种:line-height+display:inline
.container {
width: 300px;
height: 300px;
line-height: 300px;
text-align: center;
background: yellow;
}
.box {
display: inline;
background: red;
}
职场小白 south Joe,望各位大神批评指正,祝大家学习愉快!

正文完
 0