简体   繁体   English

如何将div从上到下居中?

[英]How to center a div from top to bottom?

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.我只希望 div 位于页面的中心,从上到下的间距相等,我需要使用百分比,因为 div 内容不同。 I tried bottom:50% but this does not work.我试过底部:50% 但这不起作用。

Thanks for the answers!感谢您的回答! Mine's a little different and it is my mistake for not adding this, visit my blog to 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.如果你有更好的东西,请分享,因为这显然不是最可靠的。

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%);
  }

vertical-align:center垂直对齐,然后text-align:center水平text-align:center

#mydiv {
  position:absolute;
  top:20%; bottom:20%
}

See also Understanding Vertical Align .另请参阅了解垂直对齐

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM