css水平垂直居中設置

參考:https://segmentfault.com/a/1190000003761600

水平居中

水平居中:行內元素解決方案1

父層元素添加如下屬性即可:

.parent {
    text-align:center;
}

水平居中:行內元素解決方案2-flex


水平居中:塊狀元素解決方案

.self {
    /* 這裏可以設置頂端外邊距 */
    margin: 0 auto;
}


水平居中:多個塊狀元素解決方案
將元素的display屬性設置爲inline-block,並且把父元素的text-align屬性設置爲center即可:

.parent {
    text-align:center;
}
.self{
      display:inline-block;
}


水平居中:多個塊狀元素解決方案 (使用flexbox佈局實現)
使用flexbox佈局,只需要把待處理的塊狀元素的父元素添加屬性display:flex及justify-content:center即可:

.parent {
    display:flex;
    justify-content:center;
}


垂直居中

垂直居中:單行的行內元素解決方案

.parent {
    background: #222;
    height: 200px;
}

/* 以下代碼中,將a元素的height和line-height設置的和父元素一樣高度即可實現垂直居中 */
a {
    height: 200px;
    line-height:200px; 
    color: #FFF;
}

垂直居中:多行的行內元素解決方案
組合使用display:table-cell和vertical-align:middle屬性來定義需要居中的元素的父容器元素生成效果,如下:

.parent {
    background: #222;
    width: 300px;
    height: 300px;
    /* 以下屬性垂直居中 */
    display: table-cell;
    vertical-align:middle;
}

垂直居中:已知高度的塊狀元素解決方案

.item{
    top: 50%;
    margin-top: -50px;  /* margin-top值爲自身高度的一半 */
    position: absolute;
    padding:0;
}

垂直居中:未知高度的塊狀元素解決方案

.item{
    top: 50%;
    position: absolute;
    transform: translateY(-50%);  /* 使用css3的transform來實現 */
}

水平垂直居中:已知高度和寬度的元素解決方案1
這是一種不常見的居中方法,可自適應,比方案2更智能,如下:

.item{
    position: absolute;	/*要設置寬高*/
    margin:auto;
    left:0;
    top:0;
    right:0;
    bottom:0;}


水平垂直居中:已知高度和寬度的元素解決方案2

.item{
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -75px;  /* 設置margin-left / margin-top 爲自身高度的一半 */
    margin-left: -75px;
}

水平垂直居中:未知高度和寬度元素解決方案

.item{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);  /* 使用css3的transform來實現 */
}

水平垂直居中:使用flex佈局實現


.parent{
    display: flex;
    justify-content:center;/* 水平居中 */
    align-items: center;/* 垂直居中 */
 /* 注意這裏需要設置寬高來查看水平垂直居中效果 */
    background: #AAA;
    height: 500px;
}
.chidren{
    display: flex;
    justify-content:center;/* 水平居中 */
    align-items: center;/* 垂直居中 */
 /* 注意這裏需要設置寬高來查看水平垂直居中效果 */
    background: #AAA;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章