如何使用 CSS 为所有浏览器垂直居中 div 元素?

我想用 CSS 使 div 垂直居中.我不想要表格或 JavaScript,而只想要纯 CSS.我找到了一些解决方案,但它们都缺少 Internet Explorer 6 支持.

I want to center a div vertically with CSS. I don't want tables or JavaScript, but only pure CSS. I found some solutions, but all of them are missing Internet Explorer 6 support.

<body>
    <div>Div to be aligned vertically</div>
</body>

如何在所有主流浏览器(包括 Internet Explorer 6)中垂直居中 div?

How can I center a div vertically in all major browsers, including Internet Explorer 6?

推荐答案

以下是我可以构建的最好的全方位解决方案,用于垂直和水平居中固定宽度、灵活高度内容框.它已经过测试并适用于最新版本的 Firefox、Opera、Chrome 和 Safari.

Below is the best all-around solution I could build to vertically and horizontally center a fixed-width, flexible height content box. It was tested and worked for recent versions of Firefox, Opera, Chrome, and Safari.

.outer {
  display: table;
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
}

.middle {
  display: table-cell;
  vertical-align: middle;
}

.inner {
  margin-left: auto;
  margin-right: auto;
  width: 400px;
  /* Whatever width you want */
}

<div class="outer">
  <div class="middle">
    <div class="inner">
      <h1>The Content</h1>
      <p>Once upon a midnight dreary...</p>
    </div>
  </div>
</div>

查看具有动态内容的工作示例

我内置了一些动态内容来测试灵活性,并且很想知道是否有人发现它有任何问题.它也应该适用于居中的叠加层——灯箱、弹出窗口等.

I built in some dynamic content to test the flexibility and would love to know if anyone sees any problems with it. It should work well for centered overlays also -- lightbox, pop-up, etc.

相关文章