div水平垂直居中的方式有哪些?

工作中经常涉及到盒子水平垂直居中,分别有哪些方式,现在盘点一下?


一、absolute + transform 布局 

<div class="box">
    <div class="box-sub"></div>
</div>

<style>
.box {
  position:relative;
  width:160px;
  height:160px;
  background:red;
}

.box-sub{
  position:absolute;
  top: 50%;
  left: 50%;
  z-index:9;
  transform:translate(-50%,-50%);
  width:80px;
  height:80px;
  background:green;
}
</style>
absolute + transform 布局

二、display:flex 布局

<div class="box">
    <div class="box-sub"></div>
</div>

<style>
.box{
  width:200px;
  height:200px;
  background-color:red;
  color:white;
  font-size:20px;
  font-weight:bold;
  display:flex;
  align-items:center;
  justify-content:center;
}
.box-sub {
  width:100px;
  height:100px;
  background:green;
}
</style>
display:flex 布局

三、display: grid 布局

<div class="box">
    <div class="box-sub">hello world</div>
</div>

<style>
.box {
  display: grid;
  width:200px;
  height:200px;
  background-color:red;
  color:white;
  font-size:20px;
  font-weight:bold;
}
.box-sub {
  align-self: center;
  justify-self: center;
}
</style>
display: grid 布局

四、table 布局

<table>
    <tbody>
        <tr>
            <td class="box">
                <div class="sub"></div>
            </td>
        </tr>
    </tbody>
</table>

.box {
  width:200px;
  height:200px;
  text-align: center;
  background:red;
}
.sub {
  display: inline-block;
  background:green;
  width:100px;
  height:100px;
}
table 布局

虽然还有几种方式可以实现该效果,但存在兼容性,所以这里就不介绍了

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值