1、绝对定位
.father{
width:500px;
height:500px;
background:yellow;
position:relative;
.son{
width:100px;
height:100px;
background:red;
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
}
}
2、相对位移+transform位移
.father{
width: 500px;
height: 500px;
background: yellow;
.son{
width: 100px;
height: 100px;
background: red;
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
}
3、相对位移+transform位移+margin
.father{
width: 500px;
height: 500px;
background: yellow;
.son{
width: 100px;
height: 100px;
background: red;
position: relative;
top: 50%;
margin: 0 auto;
transform: translateY(-50%);
}
}
4、相对位移+破坏非空白的折叠条件+margin
.father{
width: 500px;
height: 500px;
background: yellow;
margin: 0;
/*border: 1px solid yellow;*/ //破坏非空白的折叠条件(子元素margin-top会影响父元素位置)
padding: 0.1px; //同上作用
//overflow:hidden; //同上作用
.son{
width: 100px;
height: 100px;
background: red;
position: relative;
top: 50%;
margin: 0 auto;
margin-top: -50px;
}
}
5、flex布局
.father{
width: 500px;
height: 500px;
background: yellow;
display: flex;
align-items: center; /*定义body的元素垂直居中*/
justify-content: center; /*定义body的里的元素水平居中*/
.son{
width: 100px;
height: 100px;
background: red;
}
}
6、vertival-align:middle+伪类
.father{
width: 500px;
height: 500px;
background: yellow;
text-align: center;
&::after{
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
.son{
width: 100px;
height: 100px;
background: red;
display: inline-block;
vertical-align: middle;
}
}
7、table-cell +子元素display:inline-block
.father{
width: 500px;
height: 500px;
background: yellow;
display: table-cell;
text-align:center;
vertical-align:middle;
.son{
width: 100px;
height: 100px;
background: red;
display: inline-block;
vertical-align: middle;
}
}
8、绝对定位+计算calc
.father{
width: 500px;
height: 500px;
background: yellow;
position: relative;
.son{
width: 100px;
height: 100px;
background: red;
position: absolute;
left:-webkit-calc((500px - 100px)/2);
top:-webkit-calc((500px - 100px)/2);
left:-moz-calc((500px - 100px)/2);
top:-moz-calc((500px - 100px)/2);
left:calc((500px - 100px)/2);
top:calc((500px - 100px)/2);
}
}

网友评论