Chapter 9. CSS Stylesheets and CSS Rules

9.1 CSS Stylesheet Overview

A stylesheet is added to an HTML document by using either the HTMLLinkElement node (i.e., <link href="stylesheet.css" rel="stylesheet" type="text/css">) to include an external stylesheet or the HTMLStyleElement node (i.e., <style></style>) to define a stylesheet inline. In the following HTML document, both of these Element nodes are in the DOM and I verify which constructor constructs these nodes.

Live code

<!DOCTYPE html>
<html lang="en">
<head>

<link id="linkElement" 
  href="http://yui.yahooapis.com/3.3.0/build/cssreset/reset-min.css" 
  rel="stylesheet" type="text/css">

<style id="styleElement">
body{background-color:#fff;}
</style>

</head>
<body>

<script>

//logs function HTMLLinkElement() { [native code] }
console.log(document.querySelector('#linkElement').constructor);

//logs function HTMLStyleElement() { [native code] }
console.log(document.querySelector('#styleElement').constructor);

</script>
</body>
</html>

Once a stylesheet is added to an HTML document, it’s represented by the CSSStylesheet object. Each CSS rule (e.g., body{background-color:red;}) inside a stylesheet is represented by a CSSStyleRule object. In the following code, I verify which constructor constructed the stylesheet and each CSS rule (selector and its CSS properties and values) in the stylesheet.

Live code

<!DOCTYPE html>
<html lang="en">
<head>

<style id="styleElement">
body{background-color:#fff;}
</style>

</head>
<body>

<script>

/* logs function ...

Get DOM Enlightenment now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.