我想用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?
当前回答
要使div在页面上居中,请选中fiddle链接。
#甚高频{边距:自动;位置:绝对;顶部:0;左:0;底部:0;右:0;}.box格式{边框半径:15px;方框阴影:0 0 8px rgba(0,0,0、0.4);填充:25px;宽度:100px;高度:100px;背景:白色;}<div id=“vh”class=“box”>div垂直对齐</div>
另一种选择是使用flex框,选中fiddle链接。
.vh文件{背景色:#ddd;高度:400px;对齐项目:居中;显示:柔性;}.vh>div{宽度:100%;文本对齐:居中;垂直对齐:中间;}<div class=“vh”><div>div垂直对齐</div></div>
另一种选择是使用CSS 3转换:
#甚高频{位置:绝对;顶部:50%;左:50%;/*变换:translateX(-50%)translateY(-50%)*/转换:转换(-50%,-50%);}.box格式{边框半径:15px;方框阴影:0 0 8px rgba(0,0,0、0.4);填充:25px;宽度:100px;高度:100px;背景:白色;}<div id=“vh”class=“box”>div垂直对齐</div>
其他回答
CSS网格
正文,html{margin:0;}正文{显示:栅格;最小高度:100vh;对齐项目:居中;}<div>div垂直对齐</div>
名单上还有一个我看不到的:
.Center-Container {
position: relative;
height: 100%;
}
.Absolute-Center {
width: 50%;
height: 50%;
overflow: auto;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
border: solid black;
}
跨浏览器(包括Internet Explorer 8-Internet Explorer 10,无黑客攻击!)响应百分比和最小值/最大值-居中,不考虑填充(不考虑框大小!)必须声明高度(请参见可变高度)建议设置溢出:自动防止内容溢出(请参阅溢出)
来源:CSS中的绝对水平和垂直居中
经过大量研究,我终于找到了最终的解决方案。它甚至适用于浮动元素。查看源
.element {
position: relative;
top: 50%;
transform: translateY(-50%); /* or try 50% */
}
垂直和水平居中
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 */}
享受
这在我的情况下有效(仅在现代浏览器中测试):
.textthatneedstobecentered {
margin: auto;
top: 0; bottom: 0;
}