我想用CSS垂直居中放置一个div。我不需要表或JavaScript,只需要纯CSS。我找到了一些解决方案,但都缺少Internet Explorer 6支持。
<body>
<div>Div to be aligned vertically</div>
</body>
如何在所有主要浏览器(包括Internet Explorer 6)中垂直居中放置div?
我想用CSS垂直居中放置一个div。我不需要表或JavaScript,只需要纯CSS。我找到了一些解决方案,但都缺少Internet Explorer 6支持。
<body>
<div>Div to be aligned vertically</div>
</body>
如何在所有主要浏览器(包括Internet Explorer 6)中垂直居中放置div?
当前回答
最简单的方法是以下三行CSS:
1) 位置:相对;
2) 顶部:50%;
3) 变换:translateY(-50%);
以下是一个示例:
外部配电盘{高度:170px;宽度:300px;背景色:浅灰色;}中间分隔符{位置:相对;顶部:50%;-webkit转换:translateY(-50%);-ms变换:translateY(-50%);变换:translateY(-50%);}<div class='outer-div'><div class='middle-div'>测试文本</div></div>
其他回答
我觉得这个最有用。。。它给出了最准确的“H”布局,并且非常容易理解。
这种标记的好处是您可以在一个地方定义内容大小->“PageContent”。
页面背景的颜色及其水平边距在其相应的div中定义。
<div id="PageLayoutConfiguration"
style="display: table;
position:absolute; top: 0px; right: 0px; bottom: 0px; left: 0px;
width: 100%; height: 100%;">
<div id="PageBackground"
style="display: table-cell; vertical-align: middle;
background-color: purple;">
<div id="PageHorizontalMargins"
style="width: 100%;
background-color: seashell;">
<div id="PageContent"
style="width: 1200px; height: 620px; margin: 0 auto;
background-color: grey;">
My content goes here...
</div>
</div>
</div>
</div>
这里用CSS分隔:
<div id="PageLayoutConfiguration">
<div id="PageBackground">
<div id="PageHorizontalMargins">
<div id="PageContent">
my content goes here...
</div>
</div>
</div>
</div>
#PageLayoutConfiguration{
display: table;
width: 100%;
height: 100%;
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
}
#PageBackground{
display: table-cell;
vertical-align: middle;
background-color: purple;
}
#PageHorizontalMargins{
width: 100%;
background-color: seashell;
}
#PageContent{
width: 1200px;
height: 620px;
margin: 0 auto;
background-color: grey;
}
使用转换的三行代码实际上在现代浏览器和Internet Explorer上运行:
.element{
position: relative;
top: 50%;
transform: translateY(-50%);
-moz-transform: translateY(-50%);
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
}
我添加这个答案是因为我发现这个答案的前一个版本有些不完整(堆栈溢出不允许我简单地评论)。
如果当前div位于主体中且没有容器div,则“position”relative会破坏样式。然而,“fixed”似乎有效,但它显然会修复视口中心的内容此外,我使用这种样式对一些覆盖div进行了居中设置,并发现在Mozilla中,这个转换后的div中的所有元素都失去了底部边框。可能是渲染问题。但是,只在其中一些页面上添加最小的填充就可以正确地渲染。Chrome和Internet Explorer(令人惊讶)渲染了这些框,而不需要填充
实际上,垂直居中需要两个div。包含内容的div必须具有宽度和高度。
#集装箱{位置:绝对;顶部:50%;页边空白:-200像素;/*#内容高度的一半*/左:0;宽度:100%;}#内容{宽度:624px;左边距:自动;右边距:自动;高度:395px;边框:1px实心#000000;}<div id=“container”><div id=“content”><h1>居中的div</h1></div></div>
这是结果。
对于新手,请尝试:
display: flex;
align-items: center;
justify-content: center;
这是迄今为止最简单的方法,也适用于非阻塞元素。唯一的缺点是它是Flexbox,因此,较旧的浏览器将不支持此功能。
<div class="sweet-overlay">
<img class="centered" src="http://jimpunk.com/Loading/loading83.gif" />
</div>
指向CodePen的链接:
http://codepen.io/damianocel/pen/LNOdRp
这里重要的一点是,对于垂直居中,我们需要定义父元素(容器),并且img的高度必须小于父元素。