1. 程式人生 > >CSS之水平垂直居中

CSS之水平垂直居中

三種方法實現DIV水平垂直居中

  • 絕對定位 + margin 負值
/* html */
<div id="box"></div>

/* css */
#box{
    height:200px;
    width:400px;
    background:#ccc;
    position:absolute;
    top:50%;
    left:50%;
    margin-top:-100px; 
    margin-left:-200px;
}

要點:已知元素高和寬,將其絕對定位時,top,left定位50%,最後將margin-top 和 margin-left 設為高和寬的一半的負值。

  • 絕對定位 + translate
#box{
    height:200px;
    width:400px;
    background:#ccc;
    position: absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
}

要點:可以不知道元素高和寬,將其絕對定位時,top,left定位50%,最後translate(-50%,-50%),即移動相對於自身高和寬的-50%。

  • 絕對定位 + margin 自適應
#box{
    height:200px;
    width
:400px
; background:#ccc; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; }

要點:可以不知道元素高和寬,將其絕對定位時,top,left,bottom,right設為0,同時margin 自適應。

效果圖都一樣,就放一張:
這裡寫圖片描述

CSS圖片水平垂直居中

/* html */
<div id="box">
    <img src="./img/test.jpg" alt="">
</div>

/* css */
#box{ width: 200px; height: 200px; margin: 0 auto; border: 1px solid #41b886; text-align: center; line-height: 200px; } #box img{ //圖片設為70%,是為了方便檢視效果 width: 70%; vertical-align: middle; }

最後貼上效果圖:
這裡寫圖片描述