第一次写博客我也不知道是咋样的,对于我个人还是为了给自己增加对这个知识点的理解和记忆。
第一种:最常用的用定位再减去自身的一半
*{
padding: 0;
margin: 0;
}
.box{
width: 200px;
height: 200px;
background:#ccc;
position: relative;
}
.goods{
width: 50px;
height: 50px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -25px;
margin-left: -25px;
background:#222;
}
第二种:用display: table-cell做成表格的样式,用表格的样式来上下居中
*{
padding: 0;
margin: 0;
}
.box{
width: 200px;
height: 200px;
display: table-cell;
vertical-align: middle;
text-align: center;
background:#ccc;
position: relative;
}
.goods{
display: inline-block;/* (如果需要左右居中) */
width: 50px;
height: 50px;
background:#222;
}
第三种:利用绝对定位和translate
*{
padding: 0;
margin: 0;
}
.box{
width: 200px;
height: 200px;
background:#ccc;
position: relative;
}
.goods{
width: 50px;
height: 50px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background:#222;
}
第四种:用定位和 margin:auto(说实话这种没用过,但实用)
*{
padding: 0;
margin: 0;
}
.box{
width: 200px;
height: 200px;
background:#ccc;
position: relative;
}
.goods{
display: inline-block;
position:absolute;
top:0;
right:0;
bottom:0;
left:0;
margin:auto;
width: 50px;
height: 50px;
background:#222;
}
第五种:用CSS3的flexBox定义flex的子项在flex容器的方向,align-items:纵轴的方向, justify-content: center:横轴方向。这种在移动端用的比较多。但pc端有兼容性问题(IE10以上可以用,包括IE10)
*{
padding: 0;
margin: 0;
}
.box{
display: flex;
align-items: center;
justify-content: center;
width: 200px;
height: 200px;
background:#ccc;
position: relative;
}
.goods{
display: inline-block;
width: 50px;
height: 50px;
background:#222;
}
结语:我相信大家都知道这几种方法,我想慢慢积累自己的技术栈,有问题欢迎指正,知道的请路过!!!