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

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

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


当前回答

现在,Flexbox解决方案是现代浏览器的一种非常简单的方式,因此我向您推荐:

.容器{显示:柔性;对齐项目:居中;对齐内容:中心;高度:100%;背景:绿色;}身体html格式{高度:100%;}<div class=“container”><div>div垂直对齐</div></div>

其他回答

垂直和水平居中

HTML

<div id="dialog">Centered Dialog</div>

CSS

#dialog {
    position:fixed; top:50%; left:50%; z-index:99991;
    width:300px; height:60px;
    margin-top:-150px;  /* half of the width */
    margin-left:-30px; /* half of the height */}

享受

不回答浏览器兼容性,但也要提到新的网格和不那么新的Flexbox功能。

Grid

来自:Mozilla-网格文档-垂直对齐Div

浏览器支持:网格浏览器支持

CSS:

.wrapper {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 10px;
  grid-auto-rows: 200px;
  grid-template-areas: 
    ". a a ."
    ". a a .";
}
.item1 {
  grid-area: a;
  align-self: center;
  justify-self: center;
}

HTML格式:

<div class="wrapper">
 <div class="item1">Item 1</div>
</div>

柔性包装箱

浏览器支持:Flexbox浏览器支持

CSS:

display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
align-items: center;
justify-content: center;

使用Flexbox可以轻松将内容居中。以下代码显示了容器的CSS,其中的内容需要居中:

.absolute-center {
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;

    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;

    align-items: center;
}

这在我的情况下有效(仅在现代浏览器中测试):

.textthatneedstobecentered {
  margin: auto;
  top: 0; bottom: 0;
}

这是迄今为止最简单的方法,也适用于非阻塞元素。唯一的缺点是它是Flexbox,因此,较旧的浏览器将不支持此功能。

<div class="sweet-overlay">
    <img class="centered" src="http://jimpunk.com/Loading/loading83.gif" />
</div>

指向CodePen的链接:

http://codepen.io/damianocel/pen/LNOdRp

这里重要的一点是,对于垂直居中,我们需要定义父元素(容器),并且img的高度必须小于父元素。