Creating more intuitive code and making inheritance clear
While HTML code already has a nested structure of HTML elements, CSS code has no nesting. Sass extends CSS with nesting, which enables you to create selectors that follow the same nested structure as your HTML.
Getting ready
Read the Installing Sass for command line usage recipe of Chapter 1, Getting Started with Sass, to find out how to install Ruby Sass.
How to do it...
Learn how to make your code more intuitive by performing the steps shown beneath:
- Create a Sass template called
main.scss
that will contain the following SCSS code:// scss-lint:disable ColorKeyword $link-color: black; p { font-size: 1em; a { color: $link-color; } }
- Compile the
main.scss
file from the previous step into CSS code by running the following command in your console:sass main.scss
- You will find that the CSS code outputted to your console will look like that shown here:
p { font-size: 1em; } p a { color: black; }
How it works...
Web browsers use the hierarchy of your HTML structure to calculate CSS property values that have not been explicitly set. Consider an HTML structure like that shown here:
<div> <h2>blue</h2> </div>
Here, the font color set by the color
CSS property of the h2
HTML element inherits its value from the div HTML element. Note that the color CSS property has a default value of inheritance.
Now, you can use an SCSS code like that shown here to visualize this inheritance:
div { color: blue; h2 { font-size: 1.3em; } }
In the preceding SCSS code, it is directly clear that the nested h2
selector got a calculated color value of blue inherited from the div
element.
There's more...
Although nesting your selectors can make your code more intuitive, it can equally break other things. For instance, when considering OOCSS principles, this does not allow the nesting of headings (h1
- h6
). Headings are considered to be built-in objects in OOCSS, so their appearance should be consistent across an entire website. You can read more about OOCSS in the Applying the OOCSS, SMACSS, and BEM methodologies recipe of this chapter.
You should restrict the levels of nesting in your SCSS code. If you apply too much nesting to your selectors, your CSS will get broken for every change in your HTML structure. Read more about this topic in the Avoiding nested selectors too deeply for more modular CSS recipe of this chapter.
See also
- Read more about the inherited CSS values at https://developer.mozilla.org/en-US/docs/Web/CSS/inherit.
- To understand more about the CSS selector's performance, you can start reading the CSS performance revisited: selectors, bloat, and expensive styles article by Ben Frain. You can find this article at http://benfrain.com/css-performance-revisited-selectors-bloat-expensive-styles/.