1. 程式人生 > >CSS 元素水平,垂直居中方法

CSS 元素水平,垂直居中方法

一,行內元素:

div{ text-align:center }         /*DIV內的行內元素均會水平居中*/ 

div{ height:30px; line-height:30px }          /*DIV內的行內元素均會垂直居中*/ 

二,塊級元素:

div p{margin:0 auto; width:500px}         /*塊級元素p一定要設定寬度,才能相當於DIV父容器水平居中*/ 

塊級元素垂直居中7種方法

1,table形式居中

<div id="parent">
    <div id="child">Content here</div>
</div>
#parent {
    display: table;
}

#child {
    display: table-cell;
    vertical-align: middle;
}

2,absolute 加 margin

<div id="parent">
    <div id="child">Content here</div>
</div>
#parent {
    position: relative;
}

#child {
    position: absolute;
    top: 50%;
    left: 50%;
    height: 30%;
    width: 50%;
    margin: -15% 0 0 -25%;
}

 3,absolute 加 拉伸

<div id="parent">
    <div id="child">Content here</div>
</div>
#parent {
    position: relative;
}

#child {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 50%;
    height: 30%;
    margin: auto;
}

4,上下 padding

    <div id="parent">
        <div id="child">Content here</div>
    </div>
    #parent {
        padding: 5% 0;
    }
    #child {
        padding: 10% 0;
    }

5,浮動DIV

<div id="parent">
    <div id="floater"></div>
    <div id="child">Content here</div>
</div>
#parent {
    height: 250px;
}

#floater {
    float: left;
    height: 50%;
    width: 100%;
    margin-bottom: -50px;
}

#child {
    clear: both;
    height: 100px;
}

6,absolute 加 transform

    <div id="parent">
        <div id="child">Content here</div>
    </div>
#parent {
    position: relative;
}

#child {
    position: absolute;
    width: 100%;
    top: 50%;
    left: 0;
    text-align: center;
    transform: translateY(-50%);
}

7,flex 彈性佈局居中(PC有相容問題)

    <div id="parent">
        <div id="child">Content here</div>
    </div>
#parent {
    display: flex;
    align-items: center;
    /*垂直居中*/
    justify-content: center;
    /*水平居中*/

}