掌握盒子水平垂直居中的方案

回答步骤:
1. 首先说这种需求在我之前的项目中是十分常见的,刚开始我用了定位的方式,让盒子相对于父级元素进行定位代码如下:

body {
   position: relative;
}
.box {
   width: 100px;
   height: 50px;
   position: absolute;
   top: 50%;
   left: 50%;
   margin-left: 50px;
   margin-top: 25px;
}
  1. 第一种方案由于要知道盒子的宽高,而有一种方案不需要知道盒子的宽高。
.box {
   position: absolute;
   top: 0;
   left: 0;
   right: 0;
   bottom: 0;
   margin: auto;
}
  1. 利用CSS3的transform特性
.box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(50%, 50%);
}
  1. 后来CSS新特性有了flex布局,我发现也能做:
body {
   display: flex;
   justify-content: center;
   align-items: cneter;
}
  1. 我在看掘金的时候看到一种方法,觉得挺好玩的,就记住了
body {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
.box {
   display: inline-block;
}
  1. js方法动态设置
  2. body.style.,left = (clientX - offX) / 2 + 'px';body.style.top = (clientY- offY) / 2 + ‘px’;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值