盒子水平和垂直居中的几种方式?

163 阅读1分钟

需求:盒子需要在浏览器中水平和垂直居中(在浏览器的正中间)

一、开启flex布局

<style>
    .body {
        width: 100%;
        height: 100vh;
        /* height: 100%; */
        background: -webkit-linear-gradient(left, red, yellow, lime, aqua, blue);
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .box {
        width: 200px;
        height: 200px;
        background-color:blue;

    }
</style>

<body>
    <div class="body">
        <div class="box">
        </div>
    </div>
</body>

备注: 1.首先给父盒子宽100%,高100vh,设置背景色(方便观看) 2.开始flex布局:display:flex; 3.设置justify-content:center;(居中) 4.设置align-item:center;(垂直居中) 5.给子盒子宽和高以及背景色 ps:vh和%的区别,1vh等于屏幕高度的百分之一,也是属于一种自适应的长度单位。%要根据子盒子的高度,子盒子没有内容时候,高度为0,有盒子为盒子的高度。

二、定位的方式:

<style>
    .body {
        position: relative;
        height: 100vh;
        width: 100%;
        background-color: pink;

    }

    .box {
        position: absolute;
        top: 50%;
        right: 50%;
        width: 200px;
        height: 200px;
        margin-top: -100px;
        margin-right: -100px;
        /* 渐变 */
        background-image: linear-gradient(to right, red, rgb(49, 186, 75));

    }
</style>

<body>
    <div class="body">
        <div class="box">
        </div>
    </div>
</body>

备注: 1.子绝父相 2.子盒子top:50%, right:50%,然后再向上和右边平移一些:margin-top:-100px,margin-right:-100px (盒子的一半)

三、用transfrom属性

<style>
    .body {
        position: relative;
        height: 100vh;
        width: 100%;
        background-color: pink;

    }

    .box {
        position: absolute;
        top: 50%;
        right: 50%;
        width: 200px;
        height: 200px;
        transform: translate(100px, -100px);
        /* 渐变 */
        background-image: linear-gradient(to right, red, rgb(49, 186, 75));

    }
</style>

<body>
    <div class="body">
        <div class="box">
        </div>
    </div>
</body>

备注: 当我们用了定位,然后top:50%;right:50%的时候,可以使用transform:translate()方法移动 第一个是x轴,第二是y轴。向是上和向右移动盒子的一半

四、margin auto的方法:

<style>
    .body {
        position: relative;
        width: 100%;
        height: 100vh;
        background-color: pink;
    }

    .box {
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        margin: auto;
        width: 200px;
        height: 200px;
        background-color: purple;
    }
</style>

<body>
    <div class="body">
        <div class="box">
        </div>
    </div>
</body>

备注:用了定位的方式之后,上下左右设置成0,给个margin:auto也能实现(其中margin:auto;意思是表示四周全部自动充满)