四种垂直居中方式

2019-01-14  本文已影响0人  Christoles

方法一:

/*保证宽高比例  且  test里的img垂直居中*/
<style>
  .test1{
      width: 30%;
      height: 0;
      padding-top:30%;
      background: skyblue;
      position: relative;
      overflow: hidden;
  }         
  .test1 img{
      position: absolute;
      left: 50%;
      top:50%;
      transform: translate(-50%,-50%);
      /*错误写法:translate(-50%  -50%)   中间用空格隔开!*/
      width: 100%;
  }
</style>

<div class="test1">
    <img src="img/5_03.png" alt="" />
</div>    

效果图:


image.png

方法二:

<style>
  .test2{
      width: 500px;
      height: 500px;
      background: pink;
      position: relative;
      overflow: hidden;
  }
  .test2 img{
      width: 50%;
      position: absolute;
      left: -500px;
      top: -500px;
      bottom: -500px;
      right: -500px;
      margin: auto;
  }
</style>

<div class="test2">
    <img src="img/5_03.png" alt="" />
</div>

效果图:


image.png

方法三:

<style>
  .test3{
      width: 500px;
      height: 500px;
      background: red;
          position: relative;
      overflow: hidden;
  }
  .test3 img{
      width: 100%;
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      right: 0;
      margin: auto;
  }
</style>

<div class="test3">
    <img src="img/5_03.png" alt="" />
</div>

效果图:


image.png

方法四:vertical-align: middle

<style>
  .test4{
      width: 400px;
      height: 400px;
      background: yellow;
      line-height: 400px;
      text-align: center;
  }
  .test4 img{
      width: 50%;
      vertical-align: middle;
  } 
</style>

<div class="test4">
    <img src="img/5_03.png" alt="" />
</div>   

效果图:


image.png
上一篇下一篇

猜你喜欢

热点阅读