css垂直居中布局的实现方案

1 篇文章 0 订阅

1、居于position定位

(1)

 body {
            position: relative;
            height: 100vh;
            width: 100%;
        }

        .box-child {
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            margin: auto;
        }

备注:在这个方法中,box-child不用计算高度,但是必须有高度

(2)

 body {
            position: relative;
            height: 100vh;
            width: 100%;
        }

        .box-child {
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
           top: 50%;
            left: 50%;
            margin-left: -50px;
            margin-top: -50px;
        }

备注:.box-child必须有宽高

(3)

 body {
            position: relative;
            height: 100vh;
            width: 100%;
        }

        .box-child {
            position: absolute;
            top: 50%;
            left: 50%;
           transform: translate(-50%,-50%);
        }

备注:不必管宽高,但是不兼容

(4)

  body {
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .box-child {

        }

备注:此方法有兼容问题,主要使用flex布局

(5)利用js

<div class="box-child" id="box">544444444444</div>
<script>
    let html = document.documentElement;
    let x = html.clientWidth;
    let y = html.clientHeight;
    let box = window.document.getElementById('box');
    let boxH = box.offsetHeight;
    let boxW = box.offsetWidth;
    box.style.position = "absolute";
    box.style.left = (x - boxW) / 2 + "px";
    box.style.top = (x - boxH) / 2 + "px";

</script>

(6)

  .box {
            width: 400px;
            height: 500px;
            display:table-cell;
            vertical-align: middle;
            text-align: center;
            background: red;
        }
        .box-child{
            display: inline-block;
            background: yellow;
        }

备注:这种方法不常用,其中.box必须给定宽高

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值