父元素设置overflow: scroll, 子元素的宽度大于父元素,为什么margin-right消失了?

    <style>
    *{
        box-sizing: border-box;
    }
    .w1{
        width: 500px;
        height: 300px;
        background-color: red;
        overflow: scroll;
    }
    .w2{
        width: 1000px;
        height: 600px;
        margin: 20px;
        background-color: green;
    }
    </style>
    
    <div class="w1">
        <div class="w2"></div>
    </div>

为啥子元素的margin-right:20px 不显示?

图片描述

阅读 6.6k
5 个回答

按规范(10.3.3)

The following constraints must hold among the used values of theother properties:

'margin-left' + 'border-left-width' + 'padding-left' + 'width' +'padding-right' + 'border-right-width' + 'margin-right' = width of containing block

If 'width' is not 'auto' and 'border-left-width' + 'padding-left' +
'width' + 'padding-right' + 'border-right-width' (plus any of
'margin-left' or 'margin-right' that are not 'auto') is larger than
the width of the containing block, then any 'auto' values for
'margin-left' or 'margin-right' are, for the following rules, treated
as zero.

If all of the above have a computed value other than 'auto', the
values are said to be "over-constrained" and one of the used values
will have to be different from its computed value. If the 'direction'
property of the containing block has the value 'ltr', the specified
value of 'margin-right' is ignored and the value is calculated so as
to make the equality true. If the value of 'direction' is 'rtl', this
happens to 'margin-left' instead.

我首先注意到最后一段:如果以上(属性)的计算值都不是'auto',就说该值被过度约束(over-constrained)了,其中一个应用值将与其计算值(就是换算后的指定值)不同。如果包含块的'direction'属性值为'ltr','margin-right'的指定值会被忽略,并且为了让等式成立,需要计算该值。如果'direction'的值为'rtl',就换成'margin-left'

这里padding和border计算值都不是auto,出现了过度约束的情况,margin-right需要带入等式重新计算,但是问题是这里发生了溢出滚动,如果用上面的公式,margin-right应该是个负值才能让等式成立,到这里我也糊涂了。今天重新阅读才发现,第3段定义了溢出的情况的:溢出后如果使用下面规则进行计算的话,会把左右margin的auto值当做0来处理,(过度约束情况下的重新计算,应该可以理解为这里所说的值为auto)因此margin-right应用值是0。至于margin-right在调试工具中显示20px是因为这里显示的可能是其计算值,而不是应用值。


刚下载了servo测试,使用window.getComputedStyle(obj , null).marginRight获取到的竟然是个负值

父元素上用padding-right

父元素本来就不大,还想用margin强占更多的空间,是不是太‘过分’啦?

margin-right并没有消失,你打开控制台看一下就知道了图片描述

原因@王全能是谁 已经解释了,解决方法是给最后一个元素添加border-right: 20px solid red; border的色值跟背景一样即可。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题