css樣式的百分比都相對於誰?

margin、padding、border

width、height

position等等一些可以用百分比的樣式,都相對於誰,父級?自身?還是窗口?

看了一些資料都是一帶而過說可以用百分比表示,自己做了實驗,但不確定,想知道標準規則


相對於父元素寬度的:

[max/min-]width、left、right、text-indent、padding、margin 等;

相對於父元素高度的:

[max/min-]height、top、bottom 等;

相對於主軸長度的:

flex-basis 等;

相對於繼承字型大小的:

font-size 等;

相對於自身字型大小的:

line-height 等;

相對於自身寬高的:

border-radius、background-size、border-image-width、transform: translate()、transform-origin、zoom、clip-path 等;

相對於行高的:

vertical-align 等;

特殊演算法的:

background-position (方向長度 / 該方向除背景圖之外部分總長度 * 100)、border-image-slice (相對於圖片尺寸)、filter 系列函數等;

如果自身設置 position: absolute,「父元素」指:Boringer:破壞文檔流的div高度設為百分比是相對誰而言的?;

如果 position: fixed,「父元素」指視口。


首先要搞清一個概念,css中的布局塊都是盒子,然後一個盒子的百分比其實是相對於其包含塊的,什麼是包含塊呢,http://w3.org的相關定義如下:

In CSS 2.1, many box positions and sizes are calculated with respect to the edges of a rectangular box called a containing block. In general, generated boxes act as containing blocks for descendant boxes; we say that a box "establishes" the containing block for its descendants. The phrase "a box"s containing block" means "the containing block in which the box lives," not the one it generates.

包含塊的具體規則大致就是如下這些:

The position and size of an element"s box(es) are sometimes calculated relative to a certain rectangle, called the containing block of the element. The containing block of an element is defined as follows:

  1. The containing block in which the root element lives is a rectangle called the initial containing block. For continuous media, it has the dimensions of the viewport and is anchored at the canvas origin; it is the page area for paged media. The "direction" property of the initial containing block is the same as for the root element.
  2. For other elements, if the element"s position is "relative" or "static", the containing block is formed by the content edge of the nearest block containerancestor box.
  3. If the element has "position: fixed", the containing block is established by the viewport in the case of continuous media or the page area in the case of paged media.
  4. If the element has "position: absolute", the containing block is established by the nearest ancestor with a "position" of "absolute", "relative" or "fixed", in the following way:
    1. In the case that the ancestor is an inline element, the containing block is the bounding box around the padding boxes of the first and the last inline boxes generated for that element. In CSS 2.1, if the inline element is split across multiple lines, the containing block is undefined.
    2. Otherwise, the containing block is formed by the padding edge of the ancestor.

    If there is no such ancestor, the containing block is the initial containing block.

詳情參考這個鏈接:Visual formatting model details

不同情況下,盒子的包含塊都是不同的,這裡面也有些水分。不過一般情況下你可以根據你的經驗來判斷一個盒子的包含塊是什麼,而不用懂得這些具體的標準


推薦閱讀:

為什麼a標籤中使用img後的高度多了幾個像素?
html 裡面的 role 屬性是什麼意思和用途?
DOM 是什麼?
HTML 是什麼?

TAG:前端開發 | HTML | CSS |