我想要在页面中间居中放置一个div,我尝试了top:30%,但当窗口调整大小时偏离对齐方式。
<div id=cent></div>谢谢,吉恩
发布于 2010-03-23 14:48:02
如果你知道div的高度/宽度(例如,它将是100px x 200px),那么你可以这样做:
#cent {
position:absolute;
top:50%;
left:50%;
margin-top:-50px; /* this is half the height of your div*/
margin-left:-100px; /*this is half of width of your div*/
}更新:另一个选项:查看http://www.w3.org/Style/Examples/007/center (垂直居中)
发布于 2020-08-25 03:50:59
我知道这个问题很老了,但我偶然发现了它,将来我可能会再次寻找它。
在我的例子中,内容的高度是可变的,并且我不想使用绝对定位,所以我使用了flexbox容器。你只需要将你的内容包装在一个div中,风格如下:
.container {
min-height: 100vh; /* minimum height = screen height */
display: flex;
justify-content: center;
align-items: center;
}发布于 2019-10-21 17:56:00
我知道这个问题已经有9年的历史了,但9年后偶然发现了这个问题,也许其他人也可以这么做。
这是我的工作解决方案:
#cent {
position: absolute;
width: 500px;
height: 500px;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}通过这样做,它会将width和height设置为500px,然后将top、left、right和bottom约束设置为0,最后,通过将边距设置为auto,该框将被放在窗口的正中间。这也将是响应性的。
https://stackoverflow.com/questions/2498003
复制相似问题