已用值
使用值是 CSS 属性的值,在对 计算值 执行所有计算后得到的值。
在 用户代理 完成计算后,每个 CSS 属性都具有一个使用值。尺寸的使用值(例如,width、line-height)以像素为单位。简写属性的使用值(例如,background)与其组成属性(例如,background-color 或 background-size)以及 position 和 float 的使用值一致。
注意: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 属性(例如,display、font-size 或 line-height),计算值和使用值相同。以下是依赖布局的 CSS 2.1 属性,因此它们具有不同的计算值和使用值:(取自 CSS 2.1 更改:指定值、计算值和实际值)
background-positionbottom、left、right、topheight、widthmargin-bottom、margin-left、margin-right、margin-topmin-height、min-widthpadding-bottom、padding-left、padding-right、padding-toptext-indent
规范
| 规范 |
|---|
| 层叠样式表第 2 级修订版 2 (CSS 2.2) 规范 # used-value |