今天遇到好几个地方用到了水平垂直居中,所以来复习下。
一.固定宽高的情况下
方法1:
.big{
width: 500px;
height: 500px;
border: 1px solid #abcdef;
position: relative;
}
.small{
width: 100px;
height: 100px;
position: absolute;
border: 1px solid red;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
方法2:
.big{
width: 500px;
height: 500px;
border: 1px solid #abcdef;
position: relative;
}
.small{
width: 100px;
height: 100px;
position: absolute;
border: 1px solid red;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
方法3:
.big{
width: 500px;
height: 500px;
border: 1px solid #abcdef;
position: relative;
}
.small{
width: 100px;
height: 100px;
position: absolute;
border: 1px solid red;
top: calc(50% - 50px);
left: calc(50% - 50px);
}
二.不固定宽高情况下
方法1:
.big{
width: 500px;
height: 500px;
border: 1px solid #abcdef;
position: relative;
}
.small{
width: 100px;
height: 100px;
position: absolute;
border: 1px solid red;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
方法2:字体垂直居中
.big{
width: 400px;
height: 400px;
border: 1px solid #abcdef;
line-height: 400px;
text-align: center;
}
.small{
display: inline-block;
vertical-align: middle;
line-height: inherit;
}
方法3:字体垂直居中
.big{
width: 400px;
height: 400px;
border: 1px solid #abcdef;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.small{
display: inline-block;
}
方法4:字体垂直居中
.big{
width: 400px;
height: 400px;
border: 1px solid #abcdef;
display: flex;
justify-content: center;
align-items: center;
}
亲测有效。总结了以上几种方法,好记性不如烂笔头