抱歉乱码:
<div style="position: relative;">
<div style="position: absolute; top: 50%;">This should be vertically centered</div>
<img src="http://phaseoneimageprofessor.files.wordpress.com/2013/07/iqpw29_main_image_.jpg" width="100%" style="visibility: hidden; position: absolute;"; />
<img src="http://phaseoneimageprofessor.files.wordpress.com/2013/07/iqpw29_main_image_.jpg" width="100%" />
</div>
如您所见,文本几乎垂直居中 - 但是当您缩小宽度时,您会发现这并非 100% 精确。现在要修复什么<
最佳答案
纯 css 解决方案是为内部 div 设置一个高度,并为其添加 margin: -height/2 px。
例子:
<div style="position: absolute; top: 50%; height: 20px; margin-top: -10px;">This should be vertically centered</div>
如果不知道div的高度,可以用js获取,然后重新定位div。
会是这样的(jQuery,直接回答所以可能有一些问题,请调整它。):
$("#idDiv").css("margin-top") = parseInt($("#idDiv").height() / 2) + "px";
另一种解决方案是使用 table-cell 显示和 vertical-align: middle(我个人不喜欢它,但可能适合您的需要)。
关于html - 垂直居中的东西,在 IMG 内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21990357/