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

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

问题描述

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

<div>要垂直对齐的Div</div>

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

解决方案

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

.outer {显示:表;位置:绝对;顶部:0;左:0;高度:100%;宽度:100%;}.中间 {显示:表格单元格;垂直对齐:中间;}.内{左边距:自动;右边距:自动;宽度:400px;/* 任何你想要的宽度 */}

<div class="middle"><div class="inner"><h1>内容</h1><p>从前一个沉闷的午夜......</p>

查看动态内容的工作示例

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

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>

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

解决方案

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>

View A Working Example With Dynamic Content

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天全站免登陆