DNS

css3垂直居中4种方式

Posted by Lan on July 11, 2020

css3垂直居中4种方式

  • 未知元素宽度
    #target{
      position:absolute;
      left:50%;
      top:50%;
      transform:translate(-50%,-50%)
    }
    
  • flex
    #container{
      display:flex;
      justify-content:center;
      align-items:center;
    }
    
  • table
    body{
      display:table;
    }
    #container{
      display:table-cell;
      vertical-align:middle;
    }
    #target{ 
      display:inline-block;
    }
    
  • 元素已知宽度 ``` #target{ width:20px; height:20px; background-color:yellow; position:absolute; left:50%; top:50%; margin: -10px 0 0 -10px

} ```