image

编辑人: 独留清风醉

calendar2025-05-23

message2

visits828

垂直水平居中的实现方式都有哪些?

方法一:inline-block+text-align

<div class="parent">
  <div class="child">Demo</div>
</div>

<style>
  .child {
    display: inline-block;
  }
  .parent {
    text-align: center;
  }
</style>
  • 优点:兼容性佳(甚至可以兼容 IE 6 和 IE 7)

方法二:table+margin

<div class="parent">
  <div class="child">Demo</div>
</div>

<style>
  .child {
    display: table;
    margin: 0 auto;
  }
</style>
  • 优点:无需设置父元素样式 (支持 IE 8 及其以上版本)

方法三:absolute+transform

<div class="parent">
  <div class="child">Demo</div>
</div>

<style>
  .parent {
    position: relative;
  }
  .child {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
  }
</style>
  • 优点:绝对定位脱离文档流,不会对后续元素的布局造成影响
  • 缺点:transform 为 CSS3 属性,有兼容性问题

方法四:flex+justify-content

Demo

.parent { display: flex; justify-content: center; } /* 或者下面的方法,可以达到一样的效果 */ .parent { display: flex; } .child { margin: 0 auto; }

  • 优点:只需设置父节点属性,无需设置子元素
  • 缺点:有兼容性问题

垂直居中

方法一:table-cell + vertical-align

  <div class="parent">
    <div class="child">Demo</div>
  </div>

  <style>
    .parent {
      display: table-cell;
      vertical-align: middle;
    }
  </style>
  • 优点:兼容性好(支持 IE 8,一下版本需要调整页面结构至 table)

方法二:absolute + transform

  <div class="parent">
    <div class="child">Demo</div>
  </div>

  <style>
    .parent {
      position: relative;
    }
    .child {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
  </style>
  • 优点:绝对定位脱离文档流,不会对后续元素的布局造成影响
  • 缺点:transform 为 CSS3 属性,有兼容性问题

方法三:flex + align-items

  <div class="parent">
    <div class="child">Demo</div>
  </div>

  <style>
    .parent {
      display: flex;
      align-items: center;
    }
  </style>
  • 优点:只需设置父节点属性,无需设置子元素
  • 缺点:有兼容性问题

水平垂直居中

方法一:inline-block + text-align + table-cell + vertical-align

  <div class="parent">
    <div class="child">Demo</div>
  </div>

  <style>
    .parent {
      text-align: center;
      display: table-cell;
      vertical-align: middle;
    }
    .child {
      display: inline-block;
    }
  </style>

方法二:absolute + transform

  <div class="parent">
    <div class="child">Demo</div>
  </div>

  <style>
    .parent {
      position: relative;
    }
    .child {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
  </style>

方法三:flex + justify-content + align-items

  <div class="parent">
    <div class="child">Demo</div>
  </div>

  <style>
    .parent {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  </style>

喵呜刷题:让学习像火箭一样快速,快来微信扫码,体验免费刷题服务,开启你的学习加速器!

创作类型:
原创

本文链接:垂直水平居中的实现方式都有哪些?

版权声明:本站点所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明文章出处。
分享文章
share