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

查看:57
本文介绍了如何使"div"垂直居中所有使用CSS的浏览器的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用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 working 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.

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

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