让盒子水平居中
两大类:子盒子有宽度高度;子盒子有或者没有宽度高度都可以。
子盒子有宽度高度:
方法一:margin
margin:0 auto;
方法二:position定位(一种用margin-left,一种用calc())
用margin-left
.parent {
position:relative
}
.child {
position:absolute;
width:100px;
height:100px;
top:0px;
left:50%;
margin-left:-50px;
}
用calc()
.parent {
position:relative
}
.child {
position:absolute;
width:100px;
height:100px;
top:0px;
left:calc(50% - 50px);
}
子盒子有或者没有宽度高度都可以
方法一:
.parent {
text-align:center;
}
.child {
display:inline-block;
}
方法二:position+transform
.parent {
position:relative;
}
.child {
position:absolute;
top:0; left:50%;
transform:translate(-50%,0)
}
方法三:flex布局
.parent {
display:flex;
justify-content:center;
}
让盒子垂直居中
两大类:子盒子有宽度高度;子盒子有或者没有宽度高度都可以。
子盒子有宽度高度
方法一:position(用margin-top或者calc())
用margin-top
.parent {
position:relative;
}
.child {
position:absolute;
width:100px;
height:100px;
top:50%;
left:0;
margin-top:-50px
}
用calc()
.parent {
position:relative;
}
.child {
position:absolute;
width:100px;
height:100px;
top:calc(50% - 50px);
left:0;
}
子盒子有或者没有宽度高度都可以
方法一:position+transform
.parent {
position:relative;
}
.child {
position:absolute;
left:0;
top:50%;
transform:translate(0,-50%)
}
方法二:flex布局
.parent {
display:flex;
aligin-items:center;
}
让盒子水平垂直居中
两大类:只子盒子有宽度高度;子盒子有或者没有宽度高度都可以。
只子盒子有宽度高度
方法一:position(用margin做或者calc()做)
用margin做
.parent {
position:relative;
}
.child {
position:absolute;
width:100px;
height:100px;
top:50%;
left:50%;
margin-left:-50px;
margin-top:-50px; }
用calc()做
.parent {
position:relative;
}
.child {
position:absolute;
width:100px;
top:calc(50% - 50px);
left:calc(50% - 50px);
}
子盒子有或者没有宽度高度都可以
方法一:position+transform
.parent {
position:relative;
}
.child {
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%)
}
方法二:flex布局
.parent {
display:flex;
justify-content:center;
align-items:center;
}