In Sass, nesting CSS rules allows to define hierarchy selectors:
This will be compiled into:
Because strong and em appear within the .title rule (between the 2 curly braces {}), both will be prepended with the parent selector .title.
Nesting purpose
Because CSS priority can be tricky, it’s common to use be specific when writing selectors, by combining multiple classes/tags to prevent CSS rules to cancel each other out.
To prevent rewriting .description, let’s use the ampersand &:
You can go even further by replacing & p and & table with & to create nested selectors:
Remember HTML nesting? The indentation in Sass allows to replicate how HTML elements are nested.
Notice how we only wrote table and .emptyonce for example.
It will generate exactly the CSS we started with:
The ampersand parent selector
When you nest selectors in Sass, it basically adds a space between the parent selector and the child one. So:
The space between .parent and .child defines a hierarchy: this selector targets HTML elements with class="child" nested withinclass="parent".
Now, what if you want to use pseudo-selectors like :hover? Or you want to have a selector with joined classes? You can use the ampersand which is shortcut for the parent selector:
Notice how there is no space between .parent and either :hover or .other-class.
The .parent.other-class will target HTML elements that have class="parent other-class".
This ebook is a step by step guide in which I teach you how to build your own personal webpage from scratch, line by line, with HTML5, CSS3, and even JS.