A Webpage doesn’t only have a DOM. Learn about CSSOM

Stefan Matar
2 min readJan 5, 2021

If you are a web developer you know the DOM, and how frontend frameworks like React, Angular or Vue modify that DOM to represent changes in components.

But there is probably something that you don’t hear about a lot. Its the CSSOM: the Cascading Style-Sheet Object Model.

MDN defines the CSSOM as follows:

The CSS Object Model is a set of APIs allowing the manipulation of CSS from JavaScript. It is much like the DOM, but for the CSS rather than the HTML. It allows users to read and modify CSS style dynamically. — Read More

The browser uses the DOM and the CSSOM to create a render-tree. The render-tree takes styles like display: none from the CSSOM into consideration, as those elements will not be rendered. So basically once a component in eg. React re-renders, it basically propagated its changes to the render-tree.

Lets open up a simple website: https://www.google.com/ and open the console. Run document.styleSheets and you will be presented all the elements in the CSSOM.

And if we run document.styleSheets.item(1).cssRules[0] you can see a specific rule for the first stylesheet in the CSSOM. Lets get more specific information:

> document.styleSheets.item(1).cssRules[0].selectorText
< “body, html”
> document.styleSheets.item(1).cssRules[0].style.cssText
< “height: 100%; margin: 0px; padding: 0px;”

So as we see, the cssRules give us a JSON of a style that was defined as such:

body, html {
height: 100%;
margin: 0px;
padding: 0px;
}

Seems like a cool thing. Nice. “But Stefan”, you ask, “what does this new knowledge help me?

Well. MDN says the CSSOM is obsolete and should not be used in production. Nonetheless usages of CSSOM manipulation could be:

  • When developing locally, hot-reloading could manipulate the CSSOM instead of serving the browser a new stylesheet once we edit css. This could be a faster alternative than refreshing the whole stylesheet.
  • The CSSOM could also be inspected in order to find duplication in stylesheets. One could write a browser extension that analyzes the CSSOM automatically.
    If you want to look at the merged, computet style for an element then getComputetStyle(document.body).background is another command that can help you gather more insight into the rendered style for an element.

Even if all of these use-cases are very specific and will probably not be significant enough to bother with in a normal development environment, its still a significant part of the life-circle of a website & a headsup for how rendering elements in the browser works.

--

--