盒子水平垂直居中的五种方法总结

441 阅读1分钟
基本代码

html代码:
    <!-- 先来一个盒子 -->
    <div class="box"></div>

CSS代码:

     /* 再来基本点样式 */
     * {
         margin: 0px;
         padding: 0px;
     }

     .box {
         width: 200px;
         height: 200px;
         background: -webkit-linear-gradient(left, red, yellow, lime, aqua, blue);
         background: -o-linear-gradient(left, red, yellow, lime, aqua, blue);
         background: -moz-linear-gradient(left, red, yellow, lime, aqua, blue);
         background: linear-gradient(left, red, yellow, lime, aqua, blue);
     }

方式一: 定位

css代码:

        .box{
             /* 以body作为参考点 */
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -100px;
            margin-left: -100px;
        }

缺点:需要知道box的宽高

方式二: 定位

css代码:

        .box{
            position: absolute;
            /* 上下左右的margin都尽可能的大 */
            margin: auto;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
        }

重点是让box上下左右的margin都尽可能的大

方式三: flex布局

css代码:

   body{
            display: flex;
            justify-content: center;
            align-items: center;
        }
        /* 让body,html占满整个document文档 */
        body,html{
            height: 100%;
        }

优点:简单、快 。

需要注意的是对box的父元素进行操作,把box的父元素当做一个项目,来处理父元素的水平和垂直的富裕空间

方式四: CSS3

css代码:

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

缺点:需要知道box的宽高

和方式一类似

方式五: JS

css代码:

        .box{
            position: absolute;
        }

js代码:

        // 1、获取盒子
        let box = document.querySelector('.box')
        // 2.1、盒子宽度
        let width = box.offsetWidth
        // 2.2、盒子高度
        let height = box.offsetHeight
        // 3、获取当前屏高度幕的宽高
        let screenWidth = document.documentElement.clientWidth
        let screenHeight = document.documentElement.clientHeight
        // 4、居中处理
        box.style.top = `${(screenHeight-height)/2}px`
        box.style.left = `${(screenWidth - width)/2}px`