1. 程式人生 > >css幾種垂直居中的方式(面試常考題1)

css幾種垂直居中的方式(面試常考題1)

水平垂直居中(一)定位和需要定位的元素的margin減去寬高的一半

 <style>
        *{
            padding: 0;
            margin: 0;
        }
        .box{
            width: 300px;
            height: 300px;
            background:#e9dfc7; 
            border:1px solid red;
            position: relative;
        }
        img{
            width: 100px;
            height: 150px;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -75px;
            margin-left: -50px;
        }
    </style>
<!--html -->
<body>
    <div class="box" >
        ![](2.jpg)
    </div>
</body>

水平垂直居中(二)定位和margin:auto;

<style>
        *{
            padding: 0;
            margin: 0;
        }
        .box{
            width: 300px;
            height: 300px;
            background:#e9dfc7; 
            border:1px solid red;
            position: relative;

        }
        img{
            width: 100px;
            height: 100px;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto;
        }
    </style>
<!--html -->
<body>
    <div class="box" >
        ![](3.jpg)
    </div>
</body>

水平垂直居中(三)絕對定位和transfrom

<style>
    *{
        padding: 0;
        margin: 0;
    }
    .box{
        width: 300px;
        height: 300px;
        background:#e9dfc7; 
        border:1px solid red;
        position: relative;

    }
    img{
        width: 100px;
        height: 100px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
    }
</style>
<!--html -->
<body>
    <div class="box" >
        ![](4.jpg)
    </div>
</body>

水平垂直居中(四)diplay:table-cell

<style>
    .box{
            width: 300px;
            height: 300px;
            background:#e9dfc7; 
            border:1px solid red;
            display: table-cell;
            vertical-align: middle;
            text-align: center;
        }
        img{
            width: 100px;
            height: 150px;
            /*margin: 0 auto;*/  這個也行
        }
</style>
<!--html -->
<body>
    <div class="box" >
        ![](5.jpg)
    </div>
</body>

水平垂直居中(五)flexBox居中(移動端使用沒什麼負擔)

<style>
    .box{
            width: 300px;
            height: 300px;
            background:#e9dfc7; 
            border:1px solid red;
            display: flex;
            justify-content: center;
            align-items:center;
        }
        img{
            width: 150px;
            height: 100px;
        }
</style>
<!--html -->
<body>
    <div class="box" >
        ![](6.jpg)
    </div>
</body>