盒子的水平垂直居中幾種方法

 

<!doctype html>
<html lang="zh-cmn-Hans">
<head>
<meta charset="UTF-8">
<style>
    /*1.利用位置計算,父元素相對定位,子元素絕對定位。涉及的知識很基礎,可是有點麻煩*/
    /*.box{
        height: 400px;
        width: 400px;
        position: relative;
        background-color: red;
    }
    .con{
        height: 100px;
        width: 100px;
        background-color: blue;
        position: absolute;
        margin: 50% 0 0 50%;
        left: -50px;
        top: -50px;
    }*/

    /*2.利用CSS3的transform,子元素相對定位,向上移動自身的一半*/
    /*.box{
        height: 400px;
        width: 400px;
        background-color: red;
    }
    .con{
        height: 100px;
        width: 100px;
        background-color: blue;
        position: relative;
        margin: 0 auto;
        top: 50%;
        transform: translateY(-50%);
    }*/

    /*3.利用flex佈局,簡單粗暴,只需對父元素操做*/
    .box{
        height: 400px;
        width: 400px;
        background-color: red;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .con{
        height: 100px;
        width: 100px;
        background-color: blue;
    }
</style>
</head>
<body>
    <div class="box">
        <div class="con"></div>
    </div>
</body>
</html>

 

 

這個:html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>垂直居中</title>
    <style>
        html,
        body {
            height: 100%;
            width: 100%;
        }

        /*relative定位,top:50% 利用margin-top上移自身一半*/
        .content {
            width: 300px;
            height: 300px;
            background: blue;
            margin: 0 auto;
            position: relative;
            top: 50%;
            margin-top: -150px; /*div上移自身高度(300)的一半*/
        }

        /*利用CSS3的transform: translateY(-50%)上移自身高度一半
        .content {
            width: 300px;
            height: 300px;
            background: blue;
            margin: 0 auto;
            position: relative; 
            top: 50%; 
            transform: translateY(-50%); 
        }*/

        /*flex佈局 對父元素操做
        body {
            display: flex;
            align-items: center;
            justify-content: center; 
        }
        .content {
            width: 300px;
            height: 300px;
            background: blue;
        }*/
    </style>
</head>

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

</html>
相關文章
相關標籤/搜索