Skip to content

Commit 554f125

Browse files
Better exposition of computedStyleMap() and getComputedStyle() differences (#38214)
* Better exposition of computedStyleMap() and getComputedStyle() differences * Fixes * Update index.md * Update index.md * Update files/en-us/web/api/window/getcomputedstyle/index.md Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * Address reviews * Add see also --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
1 parent 7edaecc commit 554f125

File tree

2 files changed

+82
-73
lines changed
  • files/en-us/web/api

2 files changed

+82
-73
lines changed

files/en-us/web/api/element/computedstylemap/index.md

Lines changed: 58 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,14 @@ None.
2525

2626
### Return value
2727

28-
A {{domxref("StylePropertyMapReadOnly")}} interface.
28+
A {{domxref("StylePropertyMapReadOnly")}} object.
29+
30+
Unlike {{domxref("Window.getComputedStyle")}}, the return value contains [computed values](/en-US/docs/Web/CSS/CSS_cascade/Value_processing#computed_value), not [resolved values](/en-US/docs/Web/CSS/CSS_cascade/Value_processing#resolved_value). For most properties, they are the same, except a few layout-related properties, where the resolved value is the [used value](/en-US/docs/Web/CSS/CSS_cascade/Value_processing#used_value) instead of the computed value. See the [comparison with `getComputedStyle()`](#comparison_with_getcomputedstyle) example for details.
2931

3032
## Examples
3133

34+
### Getting default styles
35+
3236
We start with some simple HTML: a paragraph with a link, and a definition list to which
3337
we will add all the CSS Property / Value pairs.
3438

@@ -79,16 +83,68 @@ In [browsers that support `computedStyleMap()`](#browser_compatibility),
7983
you'll see a list of all the CSS properties and values.
8084
In other browsers you'll just see a link.
8185

82-
{{EmbedLiveSample("Examples", 300, 300)}}
86+
{{EmbedLiveSample("getting_default_styles", 300, 300)}}
8387

8488
Did you realize how many default CSS properties a link had? Update the `document.querySelector("a")`
8589
to `document.querySelector("p")`, and you'll notice a difference in the `margin-top`
8690
and `margin-bottom` default computed values.
8791

92+
### Comparison with getComputedStyle()
93+
94+
{{domxref("Window.getComputedStyle()")}} returns [resolved values](/en-US/docs/Web/CSS/CSS_cascade/Value_processing#resolved_value), while `computedStyleMap()` returns [computed values](/en-US/docs/Web/CSS/CSS_cascade/Value_processing#computed_value). These are usually the same, but for some properties, the resolved value is the [used value](/en-US/docs/Web/CSS/CSS_cascade/Value_processing#used_value) instead of the computed value. For example, percentage values for widths are resolved to pixel values _post-layout_, so the used values are in pixels, while the computed values are still in percentages.
95+
96+
Note that the way we present it makes the two APIs seem more similar than they are. `computedStyleMap()` contains [CSS Typed OM](/en-US/docs/Web/API/CSS_Typed_OM_API) objects, while `getComputedStyle()` contains strings. The former presents the same information in a more structured and processable way.
97+
98+
In this example, the `width` property is specified as a percentage, so the computed value is given as a percentage, but the resolved value is given in pixels. The `height` is always in pixels. The `background-color` is a named color, but it is computed to an RGB value.
99+
100+
```html
101+
<div class="container">
102+
<div class="item"></div>
103+
</div>
104+
<pre id="result"></pre>
105+
```
106+
107+
```css
108+
.container {
109+
width: 200px;
110+
height: 200px;
111+
}
112+
113+
.item {
114+
width: 50%;
115+
height: 100px;
116+
background-color: tomato;
117+
}
118+
```
119+
120+
```js
121+
const item = document.querySelector(".item");
122+
const result = document.querySelector("#result");
123+
const resolvedValues = getComputedStyle(item);
124+
const computedValues = item.computedStyleMap();
125+
126+
result.textContent = `resolvedValues.width = ${resolvedValues.width}
127+
computedValues.get("width") = ${computedValues.get("width")}
128+
129+
resolvedValues.height = ${resolvedValues.height}
130+
computedValues.get("height") = ${computedValues.get("height")}
131+
132+
resolvedValues.backgroundColor = ${resolvedValues.backgroundColor}
133+
computedValues.get("background-color") = ${computedValues.get(
134+
"background-color",
135+
)}`;
136+
```
137+
138+
{{EmbedLiveSample("comparison_with_getcomputedstyle", "", 350)}}
139+
88140
## Specifications
89141

90142
{{Specifications}}
91143

92144
## Browser compatibility
93145

94146
{{Compat}}
147+
148+
## See also
149+
150+
- {{domxref("Window.getComputedStyle()")}}

files/en-us/web/api/window/getcomputedstyle/index.md

Lines changed: 24 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,7 @@ The
1313
containing the values of all CSS properties of an element, after applying active
1414
stylesheets and resolving any basic computation those values may contain.
1515

16-
Individual CSS property values are accessed through APIs provided by the object, or by
17-
indexing with CSS property names.
16+
Individual CSS property values are accessed through APIs provided by the returned {{DOMxRef("CSSStyleDeclaration")}} object, or by indexing with CSS property names. The values returned by `getComputedStyle` are [resolved values](/en-US/docs/Web/CSS/CSS_cascade/Value_processing#resolved_value).
1817

1918
## Syntax
2019

@@ -33,8 +32,20 @@ getComputedStyle(element, pseudoElt)
3332

3433
### Return value
3534

36-
A _live_ {{DOMxRef("CSSStyleDeclaration")}}
37-
object, which updates automatically when the element's styles are changed.
35+
A _live_ {{DOMxRef("CSSStyleDeclaration")}} object, which updates automatically when the element's styles are changed.
36+
37+
Note that:
38+
39+
- The returned {{DOMxRef("CSSStyleDeclaration")}} object contains active values for CSS property _longhand_ names as well as shorthand names. For example, the returned object contains entries for {{cssxref("border-bottom-width")}} in addition to the {{cssxref("border-width")}} and {{cssxref("border")}} [shorthand property names](/en-US/docs/Web/CSS/Shorthand_properties).
40+
- Returned values are sometimes deliberately inaccurate. To avoid the "CSS History Leak" security issue, browsers may lie about the computed styles for a visited link, returning values as if the user never visited the linked URL. See [Plugging the CSS history leak](https://blog.mozilla.org/security/2010/03/31/plugging-the-css-history-leak/) and [Privacy-related changes coming to CSS `:visited`](https://hacks.mozilla.org/2010/03/privacy-related-changes-coming-to-css-vistited/) for examples of how this is implemented.
41+
- During [CSS transitions](/en-US/docs/Web/CSS/CSS_transitions), `getComputedStyle` returns the original property value in Firefox, but the final property value in WebKit.
42+
- In Firefox, properties with the value `auto` return the used value, not the value `auto`. So if you apply `top:auto` and `bottom:0` on an element with `height:30px` and a containing block of `height:100px`, Firefox's computed style for `top` returns `70px`, as 100 − 30 = 70.
43+
- For compatibility reasons, serialized color values are expressed as [`rgb()`](/en-US/docs/Web/CSS/color_value/rgb) colors if the alpha channel value is exactly `1`, and `rgba()` colors otherwise. In both cases, legacy syntax is used, with commas as separators (for example `rgb(255, 0, 0)`).
44+
45+
The returned object is the same {{DOMxRef("CSSStyleDeclaration")}} type as the object returned from the element's {{DOMxRef("HTMLElement/style", "style")}} property. However, the two objects have different purposes:
46+
47+
- The object from `getComputedStyle` is read-only, and should be used to inspect the element's style — including those set by a `<style>` element or an external stylesheet.
48+
- The `element.style` object should be used to **set** styles on that element, or inspect styles directly added to it from JavaScript manipulation or the global `style` attribute.
3849

3950
### Exceptions
4051

@@ -52,17 +63,19 @@ object, which updates automatically when the element's styles are changed.
5263
5364
## Examples
5465

66+
### Retrieving computed styles
67+
5568
In this example we style a {{HTMLElement("p")}} element, then retrieve those styles
5669
using `getComputedStyle()`, and print them into the text content of the
5770
`<p>`.
5871

59-
### HTML
72+
#### HTML
6073

6174
```html
6275
<p>Hello</p>
6376
```
6477

65-
### CSS
78+
#### CSS
6679

6780
```css
6881
p {
@@ -76,7 +89,7 @@ p {
7689
}
7790
```
7891

79-
### JavaScript
92+
#### JavaScript
8093

8194
```js
8295
const para = document.querySelector("p");
@@ -88,36 +101,11 @@ para.textContent =
88101
)}.`;
89102
```
90103

91-
### Result
92-
93-
{{EmbedLiveSample('Examples', '100%', '240px')}}
104+
#### Result
94105

95-
## Description
106+
{{EmbedLiveSample('retrieving_computed_styles', '100%', '240px')}}
96107

97-
The returned object is the same {{DOMxRef("CSSStyleDeclaration")}} type as the object
98-
returned from the element's {{DOMxRef("HTMLElement/style", "style")}} property. However,
99-
the two objects have different purposes:
100-
101-
- The object from `getComputedStyle` is read-only, and should be used to
102-
inspect the element's style — including those set by a `<style>`
103-
element or an external stylesheet.
104-
- The `element.style` object should be used to
105-
**set** styles on that element, or inspect styles directly added to it
106-
from JavaScript manipulation or the global `style` attribute.
107-
108-
The first argument must be an {{domxref("Element")}}. Non-elements, like a
109-
{{DOMxRef("Text")}} node, will throw an error.
110-
111-
## defaultView
112-
113-
In many code samples, `getComputedStyle` is used from the
114-
{{DOMxRef("document.defaultView")}} object. In nearly all cases, this is needless, as
115-
`getComputedStyle` exists on the `window` object as well. It's
116-
likely the `defaultView` pattern was a combination of folks not wanting to
117-
write a testing spec for `window` and making an API that was also usable in
118-
Java.
119-
120-
## Use with pseudo-elements
108+
### Use with pseudo-elements
121109

122110
`getComputedStyle` can pull style info from pseudo-elements (such as
123111
`::after`, `::before`, `::marker`,
@@ -140,42 +128,6 @@ Java.
140128
</script>
141129
```
142130

143-
## Notes
144-
145-
- The returned {{DOMxRef("CSSStyleDeclaration")}} object contains active values for
146-
CSS property **_longhand_** names as well as shorthand names. For example, the returned object contains entries for
147-
{{cssxref("border-bottom-width")}} in addition to the {{cssxref("border-width")}} and
148-
{{cssxref("border")}} [shorthand property names](/en-US/docs/Web/CSS/CSS_cascade/Shorthand_properties). You can query values with longhand names like
149-
{{cssxref("font-size")}} as well as shorthand names like {{cssxref("font")}}.
150-
- CSS property values may be accessed using the
151-
{{DOMxRef("CSSStyleDeclaration.getPropertyValue", "getPropertyValue(propName)")}} method or by indexing directly into the object
152-
using array or [dot notation](/en-US/docs/Learn_web_development/Core/Scripting/Object_basics#dot_notation) such as `obj['z-index']` or `obj.zIndex`.
153-
- The values returned by `getComputedStyle` are [resolved values](/en-US/docs/Web/CSS/CSS_cascade/Value_processing#resolved_value).
154-
These are usually the same as CSS 2.1's
155-
[computed values](/en-US/docs/Web/CSS/CSS_cascade/Value_processing#computed_value), but for some older properties
156-
like `width`, `height`, or `padding`, they are
157-
instead the same as [used values](/en-US/docs/Web/CSS/CSS_cascade/Value_processing#used_value). Originally, CSS
158-
2.0 defined the _computed values_ as the "ready to be used" final values of
159-
properties after cascading and inheritance, but CSS 2.1 redefined them as pre-layout,
160-
and _used values_ as post-layout. For CSS 2.0 properties,
161-
`getComputedStyle` returns the old meaning of computed values, now called
162-
**used values**. An example difference between pre- and post-layout
163-
values includes the resolution of percentages for `width` or
164-
`height`, as those will be replaced by their pixel equivalent only for
165-
_used values_.
166-
- Returned values are sometimes deliberately inaccurate. To avoid the "CSS History
167-
Leak" security issue, browsers may lie about the computed styles for a visited link,
168-
returning values as if the user never visited the linked URL. See [Plugging the CSS history leak](https://blog.mozilla.org/security/2010/03/31/plugging-the-css-history-leak/) and [Privacy-related changes coming to CSS `:visited`](https://hacks.mozilla.org/2010/03/privacy-related-changes-coming-to-css-vistited/) for examples of how this is implemented.
169-
- During [CSS transitions](/en-US/docs/Web/CSS/CSS_transitions),
170-
`getComputedStyle` returns the original property value in Firefox, but the
171-
final property value in WebKit.
172-
- In Firefox, properties with the value `auto` return the used value, not
173-
the value `auto`. So if you apply `top:auto` and
174-
`bottom:0` on an element with `height:30px` and a containing
175-
block of `height:100px`, Firefox's computed style for `top`
176-
returns `70px`, as 100 − 30 = 70.
177-
- For compatibility reasons, serialized color values are expressed as [`rgb()`](/en-US/docs/Web/CSS/color_value/rgb) colors if the alpha channel value is exactly `1`, and `rgba()` colors otherwise. In both cases, legacy syntax is used, with commas as separators (for example `rgb(255, 0, 0)`).
178-
179131
## Specifications
180132

181133
{{Specifications}}
@@ -188,4 +140,5 @@ Java.
188140

189141
- {{DOMxRef("window.getDefaultComputedStyle()")}}
190142
- {{DOMxRef("CSSStyleDeclaration.getPropertyValue", "getPropertyValue()")}}
143+
- {{domxref("Element.computedStyleMap()")}}
191144
- [Resolved value](/en-US/docs/Web/CSS/CSS_cascade/Value_processing#resolved_value)

0 commit comments

Comments
 (0)