我试图将一个 div 居中放置,但是当我调整浏览器屏幕大小时它不起作用。
如何编辑它以在调整大小时实现可调整的顶部边距?
谢谢
<script>
var h = $(window).height();
var parentHeight = h;
var childHeight = $('#a-middle').height();
$('#a-middle').css('margin-top', (parentHeight - childHeight) /2);
</script>
编辑: 答案应该在 js 中,因为 flexbox 不能在 IE-9 上工作
最佳答案
你应该坚持使用 CSS 解决方案,有几种方法可以实现这一点
.alignVertical {
position:relative;
display:inline-block;
top:50%;
transform:translateY(-50%);
}
jsfiddle:https://jsfiddle.net/jorjmt70/
或者使用 flexbox
.parent {
display:flex;
height:100vh;
background-color:red;
justify-content:center;
align-items:center;
flex-direction:column;
}
jsfiddle:https://jsfiddle.net/mdh9h876/
如果你想使用 flex box 使用 autoprefixer 来获得更深层次的浏览器支持: https://github.com/postcss/autoprefixer
关于javascript - 调整浏览器窗口大小时,如何使 div 保持在中心高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29007077/