如何垂直居中所有浏览器的div? [英] How to vertically center a div for all browsers?

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

问题描述

我想用CSS垂直居中。我不想表或JavaScript,但只有纯CSS。我发现一些解决方案,但所有的人都缺少Internet Explorer 6的支持。

 < body& 
< div> Div垂直对齐< / div>
< / body>如何在所有主要浏览器(包括Internet Explorer 6)中垂直居中一个div?

如何在所有主流浏览器中垂直居中一个div?

解决方案

下面是我可以构建的垂直&水平居中固定宽度灵活高度内容框。经过测试,适用于最新版本的FF,Opera,Chrome和Safari和MSIE 6 +。



HTML

 < div class =outer> 
< div class =middle>
< div class =inner>

< h1>内容< / h1>

< p>一旦午夜过后...< / p>

< / div>
< / div>
< / div>

CSS

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

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

.inner {
margin-left:auto;
margin-right:auto;
width:/ *任何你想要的宽度* /;
}

,请使用带有以下更改的单独样式表:

 <! -  [if lte IE 7]>< link rel =stylesheet ... /><![endif]  - > ;; 

$ b b

  .outer {
display:inline;
top:0;
}

.middle {
display:inline;
top:50%;
position:relative;
}


display:inline;
top:-50%;
position:relative;
}

查看动态内容的工作示例



我建立了一些动态内容来测试的灵活性。很想知道是否有人看到任何问题,它应该适用于中心覆盖也 - 灯箱,弹出,等等。


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 & horizontally center a fixed-width, flexible height content box. Tested and working for recent versions of FF, Opera, Chrome, & Safari, and MSIE 6+.

HTML

<div class="outer">
  <div class="middle">
    <div class="inner">

      <h1>The Content</h1>

      <p>Once upon a midnight dreary...</p>

    </div>
  </div>
</div>

CSS

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

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

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

To accommodate for IE 7 & older, use a separate style sheet with these changes:

<!--[if lte IE 7]><link rel="stylesheet... /><![endif]-->;

.outer {
    display: inline;
    top: 0;
}

.middle {
    display: inline;
    top: 50%;
    position: relative;
}

.inner {
    display: inline;
    top: -50%;
    position: relative;
}

View A Working Example With Dynamic Content

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

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

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