CSS上下居中

第一次写博客我也不知道是咋样的,对于我个人还是为了给自己增加对这个知识点的理解和记忆。

第一种:最常用的用定位再减去自身的一半


*{
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;
}

结语:我相信大家都知道这几种方法,我想慢慢积累自己的技术栈,有问题欢迎指正,知道的请路过!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值