我似乎发现了一个奇怪的边缘情况,子元素似乎使用父元素宽度而不是高度作为上边距百分比。
它也会发生在 Chrome 和 Firefox 上,那么这是预期的行为吗?如果是这样,为什么高度会从宽度导出?
要查看该错误,请将浏览器调整为比宽度更高,然后打开下面的代码。
我希望子 div 离开屏幕,但事实并非如此。如果浏览器的宽度大于高度,则 div 会比应有的距离屏幕更远。只有当浏览器完全呈正方形时,它才位于正确的位置。
<html>
<head>
<title>Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<style type="text/css">
body {
padding: 0;
margin: 0;
}
div.parent {
position: absolute;
width: 200%;
height: 100%;
}
div.a {
position: absolute;
background-color: red;
width: 50%;
height: 100%;
}
div.child {
background-color: orange;
margin-top: -100%;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="parent">
<div class="a">
<div class="child">
</div>
</div>
</div>
<script type="text/javascript">
why = $('.child').position().top + $('.child').height()
console.log(why)
what = $('.child').position().top + $('.child').width()
console.log(what)
</script>
</body>
</html>
最佳答案
来自 CSS 盒模型规范:
8.3 Margin properties: 'margin-top', 'margin-right', 'margin-bottom', 'margin-left', and 'margin'
... The percentage is calculated with respect to the width of the generated box's containing block. Note that this is true for 'margin-top' and 'margin-bottom' as well.
有点奇怪,但我确信他们有理由。
关于jquery - 是什么导致了这种奇怪的顶部边距定位边缘情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8829597/