将一个块定位到屏幕中央

将一个块定位到屏幕中央

  html代码

<div>
                <span>甜甜的 多久啊就的垃圾发货哈浪费空间的方法和</span><br>
                <span>甜甜的 多久啊就的垃圾发货哈浪费空间的方法和</span><br>
                <span>甜甜的 多久啊就的垃圾发货哈浪费空间的方法和</span><br>
                <span>甜甜的 多久啊就的垃圾发货哈浪费空间的方法和</span><br>
                <span>甜甜的 多久啊就的垃圾发货哈浪费空间的方法和</span><br>
                <span>甜甜的 多久啊就的垃圾发货哈浪费空间的方法和</span>
            </div>

1.知道宽高的情况下(宽高设定,margin)

  css

div{
             400px;
            height: 300px;
            background: green;
            position: fixed;
            left: 50%;
            top: 50%;
            margin: -150px 0 0  -200px;
        }

2,知道宽高的情况(display:box)

body{
             100vw; //屏幕的宽
            height: 100vh;//屏幕的高
            display: box;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-box-align: center;
            -webkit-box-pack: center;
        }
        div{
             300px;
            height: 300px;
            background: red;
        }

3.知道宽高的情况下

        div{
             300px;
            height: 300px;
            position: fixed;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            background: red;
            margin: auto; (一定要写)
        }

  4.在不知道所定位块的宽高的情况下

 div{
            display: inline-block;
            background: red;
            position: fixed;
            left: 50%;
            top: 50%;
            transform: translate(-50%,-50%);

        }

  

原文地址:https://www.cnblogs.com/SunShineM/p/7675919.html