讓一個 div 水平垂直居中的幾種方法

水平垂直居中有好多種實現方式,主要就分爲兩類:不定寬高定寬高,以在body下插入一個div爲例:

  • 定寬高
  1. 使用定位+margin
    element.style {
        position: absolute;
        left: 50%;
        top: 50%;
        margin-left: -250px;
        margin-top: -250px;
        width: 500px;
        height: 500px;
        background: yellow;
        z-index: 1;
    }
    
  2. 使用定位+transfrom
    element.style {
        position: absolute;
        left: 50%;
        top: 50%;
        width: 500px;
        height: 500px;
        background: yellow;
        z-index: 1;
        transform: translate3d(-50%,-50%,0);
    }
    
  3. table-cell 方式
    div.parent-box {
    	display: table;
    	width: 100%;
    }
    div.parent {
            display: table-cell;
            height: 200px;
            width: 200px;
            background-color: orange;
            text-align: center;
            vertical-align: middle;
    }
     div.child {
            display: inline-block;
            width: 100px;
            height: 100px;
            background-color: blue;
    }
    
    <div class="parent-fix">
      <div class="parent">
        <div class="child">DEMO</div>
      </div>
    </div>
    
    table-cell 是不支持設置 width: 100%; 想讓 .parent 和 其容器寬度一致最好設置一個 dispaly: table; 父容器。
  4. calc方式
     .parent {
      border: 1px solid;
      width: 1000px;
      height: 1000px;
    }
    .child {
      position: relative;
      border: 1px solid;
      width: 100px;
      height: 100px;
      top: calc(50% - 50px);
      left: calc(50% - 50px);
    }
    
  • 不定寬高:不定寬高的方法基本都適用於定寬高的情況,這裏把div的寬高按照內容展開,使用定位+transform同樣是適用的

    div.parent {
    	position: reletive;
    }
    element.style {
        position: absolute;
        left: 50%;
        top: 50%;
        background: yellow;
        z-index: 1;
        transform: translate3d(-50%,-50%,0);
    }
    
  • flex、grid方法:

    div.parent{
      display:flex;
    }
    div.child{
      margin:auto;
    }
    
    // 子元素自動垂直水平居中
    div.parent {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    

    或者

    div.parent{
      display:flex;
    }
    div.child{
      margin:auto;
    }
    
  • static 方法

    div.parent {
        font-size: 0;
        text-align: center;
        &::before {
            content: "";
            display: inline-block;
            width: 0;
            height: 100%;
            vertical-align: middle;
        }
    }
    div.child{
      display: inline-block;
      vertical-align: middle;
    }
    

    此法來自張鑫旭的《CSS世界》,原理就是:設置inline-blockvertical-align:middle後,裏面的元素會基於中間的文字準線居中對齊(學生時代的英語本子裏面寫字母,都是4條線形成三個空白區域,文字的對齊就是根據這幾條線的)vertical-align更多信息可以看看張鑫旭博文; 然後,由於僞類是position:static(默認)的,那麼僞類撐開了父元素的基準線(高度是100%),使得此時文字的基準線就是整個div.parent的中心了,另外vertical-align隻影響inline或者inline-block的,所以div.child設置vertical-align就能居中了。

    參考資料:https://muyiy.cn/question/css/52.html

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