CSS中百分比是相对于谁?

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:post

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来计算的flex

2.2 containing block的定义

翻译自MDN:this

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__rest

  2. absolute:

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

  3. fixed:

    窗口orm

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

    1). transformperspective属性的值不是none图片

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

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

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%;)

相关文章
相关标签/搜索