CSS實現水平垂直居中

不爲別的,就是爲了能信手拈來,所以整理了一份相關內容。

水平居中

  1. 如果水平居中元素爲行內元素,設置父元素 text-align:center;
  2. 如果水平居中元素爲塊級固定,則需設置margin: 0 auto;(IE6下需在父元素上設置text-align: center;,再給子元素恢復需要的值)
<body>
    <div class="content">
        測試數據 測試數據 測試數據
        測試數據 測試數據 測試數據
        測試數據 測試數據 測試數據
        測試數據 測試數據 測試數據...
    </div>
</body>

<style>
    body {
        background: #DDD;
        text-align: center; 
    }
    .content {
        width: 500px;  
        text-align: left; 
        margin: 0 auto;  
        background: orange;
    }
</style>
  1. 如果元素爲絕對定位,法一:設置父元素position爲relative,元素設left:0;right:0;margin:auto;
body{ 
    background: #DDD;
}
.content{ 
    width: 500px;   
    background: orange;
    position: absolute;
    left: 0;
    right: 0;
    margin:0 auto;
}

法二:設置父元素position爲relative,子元素設置left和負值的margin-left;

body { 
    background: #DDD;
}
.content { 
    width: 500px; 
    background: orange;
    position: absolute;
    left: 50%;
    margin-left: -250px;
}
  1. 如果元素爲浮動,該元素設置position: relative, 並且浮動方向偏移量(left或者right)設置爲50%,浮動方向上的margin設置爲元素寬度一半乘以-1
body{ 
    background: #DDD;
}
.content{ 
    width: 500px;   
    background: orange;
    float: left;
    position: relative;
    left: 50%;
    margin-left: -250px;
}
  1. 使用flex-box佈局,父元素指定justify-content屬性爲center;
body { 
    justify-content: center;
    display: flex;
}
.content { 
    width: 500px;
}

垂直居中

  1. 若元素爲單行:可設置line-height;
  2. 若元素是行內塊級元素,display: inline-block, vertical-align: middle和一個僞元素讓內容塊處於容器中央(注:該方法指針對不折行的子元素)。
body::after, .content{
    display: inline-block;
    vertical-align: middle;
}
body::after{
    content: '';
    height: 100%;
}
body {
    height: 200px;
}
  1. 將顯示方式設置爲表格,display:table-cell,同時設置vertial-align:middle;
body {
    display: table;
    width: 100%;
    height: 200px;
}

.content {
    display: table-cell;
    vertical-align: middle;
    border: 1px solid #666;
}
  1. 使用flex佈局,設置爲align-item:center;
body {
    display: flex;
    align-items: center;
    width: 100%;
    height: 200px;
    border: 1px solid #666;
}
  1. 如果元素爲絕對定位,法一:子元素中設置bottom:0,top:0,並設置margin:auto;
body { 
    background: #DDD;
}
.content { 
    width: 500px;
    height: 200px;  
    background: orange;
    position: absolute;
    bottom: 0;
    top: 0;
    margin: auto 0;
}

法二:子元素設置top:50%,margin-top值爲高度一半的負值;

body { 
    background: #DDD;
}
.content { 
    width: 500px; 
    height: 200px;
    background: orange;
    position: absolute;
    top: 50%;
    margin-top: -100px;
}

參考:

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