为什么top-top会影响绝对div的位置? [英] Why does margin-top affect the placement of an absolute div?

查看:34
本文介绍了为什么top-top会影响绝对div的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此jsFiddle中有两个div- http://jsfiddle.net/z4062jfn/-绝对定位.我没想到给div任何保证金值会影响它们的绝对位置.对于指定给顶部div(CSS的第8行注释)的margin-bottom值,这是正确的.但是给底部框(CSS的第19行注释)的边距顶部值确实将底部div位置向下移动了该数量.

I have two divs in this jsFiddle - http://jsfiddle.net/z4062jfn/ - with absolute positioning. I didn't expect any margin values given to the divs to affect their absolute position. And this is true for a margin-bottom value given to the top div (uncomment line 8 of CSS). But a margin-top value given to the bottom box (uncomment line 19 of CSS) does move the bottom div position down by that amount.

在这种情况下,有什么让边距规则覆盖绝对位置规则的?有时?

What is there in this situation that lets a margin rule override an absolute position rule - sometimes?

<div id="box1"><p>box 1</p></div>
<div id="box2"><p>box 2</p></div>

推荐答案

关于发生这种情况的简单事实解释是偏移属性 top right 底部 left 实际上尊重每一侧的相应边距属性.规范表示,这些属性指定了边沿从该特定边偏移.边距边缘在第8.1 节中定义.

The simple factual explanation for why this happens is that the offset properties top, right, bottom and left actually respect the corresponding margin properties on each side. The spec says that these properties specify how far the margin edge of a box is offset from that particular side. The margin edge is defined in section 8.1.

因此,当您设置顶部偏移时,将考虑顶部边距,而当您设置左侧偏移时,将考虑左侧边距.

So, when you set a top offset, the top margin is taken into account, and when you set a left offset, the left margin is taken into account.

如果您设置了底部偏移而不是顶部偏移,则会看到底部边距生效.如果您随后尝试设置上边距,则上边距将不再起作用.

If you had set the bottom offset instead of the top, you'll see that the bottom margin takes effect. If you then try to set a top margin, the top margin will no longer have any effect.

如果您设置 both 的顶部和底部偏移量,以及 b 顶部和底部边距,高度,则这些值将超过-constrained且底部偏移量无效(进而底部边距也无效).

If you set both the top and bottom offsets, and both top and bottom margins, and a height, then the values become over-constrained and the bottom offset has no effect (and in turn neither does the bottom margin).

如果您想了解规范为何以这种方式定义偏移量,而不是为什么浏览器以这种方式行为,那么它主要是基于观点的,因为您所得到的只是猜测.也就是说, Fabio的解释非常合理.

If you're looking to understand why the spec defines offsets this way, rather than why browsers behave this way, then it's primarily opinion-based, because all you'll get is conjecture. That said, Fabio's explanation is quite reasonable.

这篇关于为什么top-top会影响绝对div的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆