为什么margin-right无效?

3,531 阅读2分钟

案例是这样的

HTML代码

<div class="father">
  <div class="son">我是子元素</div>
</div>

CSS代码

*{
  padding:0;
  margin:0;
  direction:ltr;
}
body{
  background-color:blue;
}
.father{
  width:200px;
  height:100px;
  background-color:red;
  margin:100px auto;
}

.son{
  width:100px;
  height:20px;
  background-color:pink;
}

初始结构如下图 当我让子元素设置margin-left为-25px,理想结果子元素应该向左移动25px

.son{
margin-left:-25px;
}

根据上图确实也实现了子元素向左移动25px,那么按常规我设置指定margin-right值应该也可以达到这样的效果

根据父元素的宽度为200px,子元素宽度为100px,要让子元素向左移动25px,可以设置margin-right:125px,即与右边距离125px

.son{
margin-right:125px;
}

what???居然没变,简直打破三观,几经查阅,终于在CSS规范里看到了结果 CSS相关规范

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

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

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.

规范中说道:'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = 包含块的宽度

如果上述所有的属性指定了非'auto'的值,这些值被称为是“过度约束”,其中之一的计算值将不得不和它的指定值不同。如果'direction'属性为'ltr','margin-right'的指定值被忽略,并重新计算以满足上面的等式。如果'direction'为'rtl',对'margin-left'采取上述的方法。

所以到这里答案就已经很明朗了,当我们指定direction为ltr即块的水平书写格式是从左到右,当上述所以属性都不是auto值时,我设置的margin-right:125px会被忽略,然后根据重新重新计算,算得margin-right为100px,所以不会出现块左移的情况。