CSS居中的几种方式

2017-08-16  本文已影响0人  被遗忘的传说

1.水平居中的 margin:0 auto;

<style>
    *{
        padding: 0;
        margin: 0;
    }
        .box{
            width: 300px;
            height: 300px;
            border: 3px solid red;
            /*text-align: center;*/
        }
        img{
            display: block;
            width: 100px;
            height: 100px;
            margin: 0 auto;
        }
    </style>

<!--html-->
<body>
    <div class="box">
        ![](1.jpg)
    </div>
</body>

2.水平居中 text-align:center;

<style>
    *{
        padding: 0;
        margin: 0;
    }
        .box{
            width: 300px;
            height: 300px;
            border: 3px solid red;
            text-align: center;
        }
        img{
            display: inline-block;
            width: 100px;
            height: 100px;
            /*margin: 0 auto;*/
        }
    </style>

<!--html-->
<body>
    <div class="box">
        ![](1.jpg)
    </div>
</body>

3.水平垂直居中 定位和需要定位的元素的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" >
        ![](1.jpg)
    </div>
</body>

4.水平垂直居中 定位和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" >
        ![](1.jpg)
    </div>
</body>

5.水平垂直居中绝对定位和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" >
        ![](1.jpg)
    </div>
</body>
上一篇 下一篇

猜你喜欢

热点阅读