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

相關文章
相關標籤/搜索