2

1. 用到百分比的属性:

  1. width, height
  2. margin, padding
  3. top, right, bottom, left
  4. transform - translate
  5. background-position, background-size

2. containing block

2.1 为什么要知道containing block

MDN:

The size and position of an element are often impacted by its containing block. Most often, the containing block is the content area of an element's nearest block-level ancestor, but this is not always the case. In this article, we examine the factors that deterime an element's containing block.

所以百分比都是相对于其containing block来计算的

2.2 containing block的定义

翻译自MDN:

containing block的定义和元素的postion属性有关:

  1. static 或 relative时:

    最近的__block container__(比如inline-block, block, list-item)或者创建了__formatting context__(比如table container, flex container, grid container或block container)的祖先元素的__context box__

  2. absolute:

    最近的position属性不是static的祖先元素的__padding box__

  3. fixed:

    窗口

  4. 特殊情况, fixed或absolute时, 当其父元素有以下情况出现时, containing block为其父元素的__padding box__:

    1). transformperspective属性的值不是none

    2). will-change属性的值是transformperspective

    3). filter属性不是nonewill-change属性的值是filter(只在Firefox中有效)

3. 如何计算

  1. height, top, bottom根据其containing block的height进行计算, 如果该height没有指定(根据内容自适应), 那么计算值为0
  2. width, left, right, padding, margin根据其containing block的width进行计算
  3. transform - translate, translateX, translateY, 根据__自身元素__的实际宽度计算
  4. background:

    4.1 background-position根据__自身元素(不是containing block)__的宽高计算

    4.2 background-size根据图片的大小进行计算. 需要注意的时, 当使用单个百分比(比如background-size: 50%;)计算时, height会隐式设为auto, 当其height计算出来的值大于容器的高度时, 超出部分会隐藏. 如果需要全部显示, 需要明确设置宽和高的值(比如, background-size: 50% 50%;)


michael
25 声望1 粉丝