如何让子元素在父元素中水平垂直居中七种方法?
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,望各位大神批评指正,祝大家学习愉快!
相关推荐
冰蝶 2020-01-10
Ladyseven 2020-10-22
luofuIT成长记录 2020-09-22
Mynamezhuang 2020-09-18
李鴻耀 2020-08-17
yaodilu 2020-08-03
zhoujiyu 2020-06-28
89510194 2020-06-27
CaiKanXP 2020-06-13
MaureenChen 2020-06-12
Phoebe的学习天地 2020-06-07
淡风wisdon大大 2020-06-06
buttonChan 2020-06-06
xtuhcy 2020-05-20
AlisaClass 2020-05-18
赵家小少爷 2020-05-16