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

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

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


当前回答

通过使用transform属性,我们可以轻松地进行垂直居中的div。

.main分区{背景:无重复滚动0 0#999;字体大小:18px;高度:450px;最大宽度:850px;填充:15px;}.垂直中心{背景:无重复滚动0 0#1FA67A;颜色:#FFFFFF;填充:15px;位置:相对;顶部:50%;变换:translateY(-50%);-moz变换:translateY(-50%);-webkit转换:translateY(-50%);-ms变换:translateY(-50%);-o变换:translateY(-50%);}<div class=“main div”><div class=“垂直中心”><span>“Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incident ut labour et dolore magna aliqua。ut enim ad minim veniam,quis nostrud exerciation ullamco labours nisi ut aliquip ex a commo consequat。Duis aute irure dolor in representate velit esse cillum dolore eu fugiat nula pariator。例外情况下,在非政府组织的支持下,必须承担责任。”我正式任命了一位不称职的莫利特。“”</span></div></div>

请参阅此处了解全文

其他回答

不回答浏览器兼容性,但也要提到新的网格和不那么新的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;

垂直和水平居中

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,因此,较旧的浏览器将不支持此功能。

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

指向CodePen的链接:

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

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

最简单的解决方案如下:

.外部div{宽度:100%;高度:200px;显示:柔性;边框:1px实心#000;}.内部div{边距:自动;文本对齐:居中;边框:1px纯红色;}<div class=“outer div”><div class=“inner div”>嘿!</div></div>

我这样做了(相应地改变宽度、高度、顶部边距和左侧边距):

.wrapper {
    width: 960px;
    height: 590px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -295px;
    margin-left: -480px;
}
<div class="wrapper"> -- Content -- </div>