父元素没有固定宽高
水平垂直居中
html:
<div class="wrapper">
<div class="info">
垂直居中
</div>
</div>
css:
//绝对定位水平垂直居中,方法1
.info {
position: absolute;
width: 500px;
height: 300px;
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
background-color: green;
}
//方法2
.info {
position: absolute;
width:300px;
height:200px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: green;
}
水平居中
//方法1
.wrapper{
display: flex;
justify-content: center;
}
.info {
width:300px;
height:200px;
background-color: green;
}
//方法2
.info {
width: 300px;
height: 200px;
margin: auto;
background-color: green;
}
不确定子元素宽高
设置水平居中,先将子元素转化为行内元素,即display:inline;或者display:inline-block;,给父元素设置text-align:center;。这是方法一
.wrapper {
    width: 500px;
    height: 500px;
    border: 1px solid red;
    text-align: center;
}
.info {
    display: inline;
    margin: 0 auto;
    background-color: green;
}方法二:使用定位居中
.wrapper {
    width: 500px;
    height: 500px;
    border: 1px solid red;
    position: relative;
}
.info {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    background-color: green;
}方法三:使用flex在弹性布局
.wrapper {
    width: 500px;
    height: 500px;
    border: 1px solid red;
    display: flex;
    justify-content: center;
}
.info {
    //这里可以设置高度
    background-color: green;
}垂直居中
方法一:
.wrapper {
    width: 500px;
    height: 500px;
    border: 1px solid red;
    display: table-cell;
    vertical-align: middle;
}
.info {
    background-color: green;
}方法二:
.wrapper {
    width: 500px;
    height: 500px;
    border: 1px solid red;
    position: relative;
}
.info {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    background-color: green;
}如果确定子元素高度,则:
.wrapper {
    width: 500px;
    height: 500px;
    border: 1px solid red;
    position: relative;
}
.info {
    height:100px;
    position: absolute;
    top: 50%;
    margin-top:-50px;
    background-color: green;
}方法三:使用flex(高定不定都可以)
.wrapper {
    width: 500px;
    height: 500px;
    border: 1px solid red;
    display: flex;
    justify-content: center;
    align-items: center;
}
.info {
    background-color: green;
}                










