用CSS/CSS3 實現 水平居中和垂直居中的完整攻略

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

只需要把行內元素包裹在一個屬性display爲block的父層元素中,並且把父層元素添加如下屬性即可:

 
.parent {
    text-align:center;
}

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

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

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

 
.parent {
    text-align:center;
}

水平居中:多個塊狀元素解決方案 (使用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;
}

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

.item{
    position: absolute;
    margin:auto;
    left:0;
    top:0;
    right:0;
    bottom:0;
}

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

.item{
    position: absolute;
    top: 50%;
    left: 50%;    width:150px;    height:150px;
    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: 300px;
}
發佈了36 篇原創文章 · 獲贊 37 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章