【发布时间】:2017-10-28 19:25:01
【问题描述】:
在使用“常规”方法努力将div 垂直居中在body 元素内之后,我决定创建一个小的jQuery 函数来计算元素需要离顶部多远“居中”。
它是这样工作的:
- 获取容器高度,
- 获取孩子身高,
- "top" = "(container.height - child.height) / 2"
- 将子元素的顶部边距设置为 "top" 的值。
例如,如果body 的宽度和高度为1000px,而此body 的div.inner 子级的宽度和高度为400px,则margin-top 的div.inner 将是300px 因为(1000-400) / 2 = 300。
这是一个图表,可以进一步解释我的意思:
注意:X 代表div.inner 的margin-top(因为我没有足够的空间放置“Margin Top =”)。
令我惊讶的是,这确实有效!!!下面是测试代码:
// set the margin top for ".vertical-centre" elements
$(".vertical-centre").each(function() {
// set the margin-top for the child
$(this).css("margin-top", function() {
// NOTE: margin = (container.height - child.height) / 2
var margin = ($(this).parent().height() - $(this).height()) / 2;
// default the margin to zero if it's a negative number
// round the margin down to the nearest whole number
// specify that the margin-top is in pixels
return Math.floor(Math.max(0, margin)) + "px";
});
});
body {
width: 100px;
height: 100px;
margin: 0;
padding: 0;
border: 1px solid black
}
div.inner {
width: 40px;
height: 40px;
background-color: blue
}
.horizontal-centre {
display: block;
margin-left: auto;
margin-right: auto
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inner horizontal-centre vertical-centre"></div>
注意:我将上面的示例缩小了,以便您可以正确查看。
不幸的是,现在还有另一个问题,当我调整浏览器大小时,div.inner 元素的margin-top 保持不变。
我希望它能够响应并在调整窗口大小时将其margin-top 属性更新为适当的值,否则div.inner 将消失,页面将如下所示:
【问题讨论】:
标签: javascript jquery vertical-alignment viewport window-resize