水平垂直居中的方式

105 阅读1分钟

1.居中元素需要定宽高 absolute+负margin

    .outer{
            width: 400px;
            height: 400px;
            border:1px solid green;
            position:relative
        }
        .inner{
            position:absolute;
            width: 150px;
            height: 150px;
            background-color: pink;
            left:50%;
            top:50%;
            margin-left:-75px;
            margin-top:-75px;
        }

2.absolute+auto

     .out{
            width: 400px;
            height: 400px;
            border:1px solid green;
            position:relative
        }
        .inner{
            position:absolute;
            width: 150px;
            height: 150px;
            background-color: pink;
            left:0;
            top:0;
            right:0;
            bottom:0;
            margin:auto;
           
        }

3.absolute + calc

   .out{
            position: relative;
        }

        .inner {
            position: absolute;
            ;
            top: calc(50% - 50px);
            left: calc(50% - 50px);
        }

4.使用flex布局方式(子元素不需要定宽高)

       .outer{
            width: 400px;
            height: 400px;
            border:1px solid green;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .inner{
            width: 150px;
            height: 150px;
            background-color: pink;
        }

5.transform

     .out{
            width: 400px;
            height: 400px;
            border:1px solid green;
            position:relative;
        }
        .inner{
            position:absolute;
            width: 100px;
            height: 100px;
            background-color: pink;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
           
        }