讓行內元素(如圖片)在div中水平垂直居中 (乾貨)

(1)第一種:用vertical-align

<div class="method1">
  <span class="tiptop"></span>
  <iimg class="test" src="img/Dota2.jpg" alt="dota2">
</div>
 
 
<style>
.method1{
  text-align:center;
}
/*vertical-align:middle  是依賴div內子元素最高的行高來實現對某元素居中的,而我們只需要建立一個新元素,給他加上inline-block屬性 再把他高度設置爲100%就行了,在下面的![在這裏插入圖片描述]()設置vertical-align就生效了*/
.tiptop{
  height:100%;
  display:inline-block;
  vertical-align:middle;
}
img{
  vertical-align:middle;
}
</style>

(2)第二種:flex佈局(注意瀏覽器兼容性)

    <div class="method2">
    <iimg src="img_p1_title.png">
    </div>
     
     
    <style>
    .method2 {
      display: flex;
      justify-content: center;  //彈性盒子對象在主軸上的對齊方式
      align-items: center;      //定義flex子項在flex容器的當前行的側軸(縱軸)方向上的對齊方式。
      background-color:#00a0e9;
      height:200px;
    }
    .method2 img {
      width:20px;
      height:30px;
      background-color:#0A58A0;
    }
    </style>

(3)position:absolute;絕對定位方式

    <div class="method3">
      <span>第三種方法</span>
    </div>
          
    <style>
    .method3 {
      width:100%;
      height: 200px;
      font-size: 18px;
      position: relative;
      background-color:#00a2d4;
    }
    .method3 span {
      width:100px;
      height:100px;
      background-color:#00ACED;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      }
    </style>

(4)使用display:table-cell配合vertical-align:center(淘寶也是這樣用的)

    <div class="method4">
      <span>第四種方法</span>
    </div>
     
     
    <style>
    .method4 {
      width: 200px;
      height: 200px;
      vertical-align: middle;
      display: table-cell;  /*只支持IE8+及現代瀏覽器,與position:absolute;或float:left;屬性儘量不一起用*/
      text-align: center;
      background-color:#00ACED;
    }
    .method4 span{
      width:100px;
      height:100px;
      background-color:#0A58A0;
    }
    </style>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章