div垂直居中的方法

方法一:margin:auto法

定義上下左右爲0,margin:auto,實現脫離文檔流的居中

//css
.div1 {
   position: relative;
     width: 200px;
     height: 200px;
     border: 3px solid forestgreen;
     margin-bottom: 20px;
 }

 .div2 {
     position: absolute;
     width: 100px;
     height: 100px;
     background: goldenrod;
     margin: auto;
     top: 0;
     left: 0;
     right: 0;
     bottom: 0;
 }
//html
<div class="div1">
    <div class="div2">
        margin:auto法
    </div>
</div>

在這裏插入圖片描述

方法二:margin負值法

// css
.div3 {
   position: absolute;
    width: 100px;
    height: 100px;
    background: goldenrod;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
    /* 或者      */
    /* transform: translateX(-50%);
    transform: translateY(-50%); */
}
  // html
 <div class="div1">
      <div class="div3">
          margin負值法
      </div>
  </div>

在這裏插入圖片描述

方法三:利用table-cell(未脫離文檔流)

設置父元素的display:table-cell,並且vertical-align:center,這樣可以讓子元素的div實現垂直居中。

    //css
    .div4 {
        position: relative;
        width: 200px;
        height: 200px;
        border: 3px solid forestgreen;
        margin-bottom: 20px;
        display: table-cell;
        vertical-align: middle;
        text-align: center;
    }

    .div5 {
        width: 100px;
        height: 100px;
        background: goldenrod;
    }
	// html
  <div class="div4">
      <div class="div5">
           table-cell
       </div>
   </div>

在這裏插入圖片描述

方法四:利用flex

將父元素設置爲display: flex;,並且設置align-items: center;justify-content: center;

// css
 .div6 {
    position: relative;
     width: 200px;
     height: 200px;
     border: 3px solid forestgreen;
     display: -webkit-flex;
     display: flex;
     -webkit-align-items: center;
     align-items: center;
     -webkit-justify-content: center;
     justify-content: center;
 }

 .div7 {
     width: 100px;
     height: 100px;
     background: goldenrod;
 }
// html
 <div class="div6">
    <div class="div7">
         利用flex
     </div>
 </div>

在這裏插入圖片描述

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