如何使用 CSS 为所有浏览器垂直居中 div 元素? [英] How can I vertically center a div element for all browsers using CSS?

查看:40
本文介绍了如何使用 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.

这篇关于如何使用 CSS 为所有浏览器垂直居中 div 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆