Html 如何将div从上到下居中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4687923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to center a div from top to bottom?
提问by Earl Larson
I just want the div to be in the center of the page, equal spacing from top to bottom and I need to use percents because the div content varies. I tried bottom:50% but this does not work.
我只希望 div 位于页面的中心,从上到下的间距相等,我需要使用百分比,因为 div 内容不同。我试过底部:50% 但这不起作用。
Hey guys, thanks for the answers! Mine's a little different and it is my mistake for not adding this, visit my blogto view the issue.
嘿伙计们,感谢您的回答!我的有点不同,没有添加这个是我的错误,请访问我的博客查看问题。
Hey everyone, thanks for using your time to answer such a stupid question, but I found that the easiest way is to just use padding:
大家好,感谢您花时间回答这么愚蠢的问题,但我发现最简单的方法是使用填充:
padding-top:X%;
padding-bottom:X%;
Then just mess with it to see what your result is. If you have anything better PLEASE DO SHARE because this is obviously probablly not the most reliable.
然后把它弄乱看看你的结果是什么。如果你有更好的东西,请分享,因为这显然不是最可靠的。
回答by Stephen Shutters
Your answer of using percentages in padding doesn't work in all situations. This is because padding percentages are based on the width of the element you are adding padding to and not the height of it. Plus, it's not at all based on the container you want the element centered within. So if you were to decrease the width of your browser window, your DIV would move to a location that is no longer centered within the browser window because the width of the DIV has changed, causing the percentage value of your padding to change as well.
您在填充中使用百分比的答案并不适用于所有情况。这是因为填充百分比基于您添加填充的元素的宽度,而不是它的高度。另外,它根本不是基于您希望元素居中的容器。因此,如果您要减小浏览器窗口的宽度,您的 DIV 将移动到浏览器窗口中不再居中的位置,因为 DIV 的宽度发生了变化,从而导致填充的百分比值也发生了变化。
To truly center your DIV no matter the browser window dimensions, the code below should help tremendously:
无论浏览器窗口尺寸如何,要真正使 DIV 居中,下面的代码应该会很有帮助:
.div {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
回答by tekknolagi
vertical-align:center
for vertically aligning
then text-align:center
for horizontal
vertical-align:center
垂直对齐然后text-align:center
水平对齐
回答by Phrogz
回答by Fuad Pa?ayev
#div{
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
height:100px;
width:100px;
}
this code aligns either bottom to top,or left to right but you have to set width and height.
Or use this:
此代码从下到上或从左到右对齐,但您必须设置宽度和高度。
或者使用这个:
#div{
display:flex;
align-items:center;
}