已用值

使用值CSS 屬性的值,在對 計算值 執行所有計算後得到的值。

使用者代理 完成計算後,每個 CSS 屬性都具有一個使用值。尺寸的使用值(例如,widthline-height)以畫素為單位。簡寫屬性的使用值(例如,background)與其組成屬性(例如,background-colorbackground-size)以及 positionfloat 的使用值一致。

注意:getComputedStyle() DOM API 返回 解析值,該值可能是 計算值 或使用值,具體取決於屬性。

示例

此示例計算並顯示三個元素的 width 使用值(在調整大小後更新)

HTML

html
<div id="no-width">
  <p>No explicit width.</p>
  <p class="show-used-width">..</p>

  <div id="width-50">
    <p>Explicit width: 50%.</p>
    <p class="show-used-width">..</p>

    <div id="width-inherit">
      <p>Explicit width: inherit.</p>
      <p class="show-used-width">..</p>
    </div>
  </div>
</div>

CSS

css
#no-width {
  width: auto;
}

#width-50 {
  width: 50%;
}

#width-inherit {
  width: inherit;
}

/* Make results easier to see */
div {
  border: 1px solid red;
  padding: 8px;
}

JavaScript

js
function updateUsedWidth(id) {
  const div = document.getElementById(id);
  const par = div.querySelector(".show-used-width");
  const wid = window.getComputedStyle(div)["width"];
  par.textContent = `Used width: ${wid}.`;
}

function updateAllUsedWidths() {
  updateUsedWidth("no-width");
  updateUsedWidth("width-50");
  updateUsedWidth("width-inherit");
}

updateAllUsedWidths();
window.addEventListener("resize", updateAllUsedWidths);

結果

與計算值的區別

CSS 2.0 僅將計算值定義為屬性計算的最後一步。然後,CSS 2.1 引入了使用值的明確定義。然後,元素可以顯式地繼承父級的寬度/高度,父級的計算值為百分比。對於不依賴佈局的 CSS 屬性(例如,displayfont-sizeline-height),計算值和使用值相同。以下是依賴佈局的 CSS 2.1 屬性,因此它們具有不同的計算值和使用值:(取自 CSS 2.1 更改:指定值、計算值和實際值

  • background-position
  • bottomleftrighttop
  • heightwidth
  • margin-bottommargin-leftmargin-rightmargin-top
  • min-heightmin-width
  • padding-bottompadding-leftpadding-rightpadding-top
  • text-indent

規範

規範
層疊樣式表第 2 級修訂版 2 (CSS 2.2) 規範
# used-value

另請參閱