非替换块级元素在normal flow的计算

发布于 2022-09-05 23:02:20 字数 2843 浏览 7 评论 0

最近在看css2规范的这个部分
https://www.w3.org/TR/CSS2/vi...

一开始它给出的这个公式

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

然后后面给出了一大堆if ...
一开始我以为这个公式是告诉你containing block的宽度怎么计算的,但是后来想想

包含块(Containing Block)是视觉格式化模型的一个重要概念,它与框模型类似,也可以理解为一个矩形,而这个矩形的作用是为它里面包含的元素提供一个参考,元素的尺寸和位置的计算往往是由该元素所在的包含块决定的。

通常情况下,一个块级元素就能作为Containing Block,那么宽度的计算公式不就是那些什么IE盒模型,标准盒模型宽度的计算公式,为什么要在规范这个地方重复了?我觉得我理解错了。

后面又想,可以这样认为,width of containing block是现有的,这公式(配合那几个if...)是告诉我们,在containing block内,被包含的块的width,margin是如何计算的,比如规范其中一个if...

If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.

这句告诉我们,如果被包含块的margin-left/right被设置为auto,那么margin-left/right则相等

比如width:500px,width of containing block为1000px,padding,border不设置则视为0

margin-left+margin-right+width=width of containing block
即
x+x+500px=1000px
所以margin-left=margin-right=250px

那么我的问题有两个

  1. width of containing block是现有的,这公式(配合那几个if...)是告诉我们,在containing block内,被包含的块的width,margin是如何计算的 这句我是否理解错了
  2. 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.

如何理解这条规范

我尝试用这段代码理解

<div style="border:1px solid red;height:200px;width: 300px;direction: ltr;">
        <div style="display: inline-block;width:30px;height:30px;border: 1px blue solid;margin-left: 76px;margin-right: 262px;"></div><div style="display: inline-block;width:30px;height:30px;border: 1px blue solid;margin-left: 24px;margin-right: 98px;"></div>
    </div>

clipboard.png

我以为第一个蓝色块的margin-right会被忽略,但并没有


经过 王能全是谁 同学的指点改正了代码,这节规范讲的是块级元素

clipboard.png

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

弃爱 2022-09-12 23:02:20

inline-block是内联级元素,计算规则在10.3.9

蓝眼泪 2022-09-12 23:02:20

Overconstrained这个概念我也心生疑问 margin-right并没有被忽略..

clipboard.png

clipboard.png

柠栀 2022-09-12 23:02:20

这几节都是讲元素在 containing block 里怎么计算宽高和位置的,之所以再单独划分一章是因为太多情况。

你最后的例子里 margin-right 是真的被忽略了。这个忽略不是说它的值没了,而是计算位置时忽略了。这种情况属于 over-constrained,只取了 margin-left 的值,子元素到 containing block 右边的距离明显比 margin-right 短。

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文