- Mastering PostCSS for Web Design
- Alex Libby
- 490字
- 2021-07-14 11:12:25
Introducing nesting
The concept of nesting is nothing new when using processors such as Less CSS or SASS; it's a useful technique to help reduce the amount of code we need to write, and to organize code in a more human-readable format.
The flipside of the coin is that it is frequently abused—when using processors for the first time, many developers fall into the trap of thinking that everything should be nested. One can get away with it if the code is very simple; it is more likely to result in fragile code that is difficult to read and easily broken with simple changes to one or more styles in the code.
If nesting is done correctly, then it can be very effective; it helps avoid the need to repeat parent selectors, and allows us to group together rules that apply to the same selector, together. To see what is meant by this, take a look at this simple example for SASS:
#main p { color: #00ff00; width: 97%; .redbox { background-color: #ff0000; color: #000000; } }
If this is compiled using a GUI application or via the command line, it results in these styles:
#main p { color: #00ff00; width: 97%; } #main p .redbox { background-color: #ff0000; color: #000000; }
The great thing about this code is that we've not tried to cram in every single rule that applies to the same parent selector, or a descendant; this is something we should consider when working with nesting.
Note
Notice how, in our SASS example, the nesting was at the end of the code? It's considered good practice to include nested statements at the end, before the closing bracket.
Some developers counsel against using nesting though, as it causes real issues for elements that have been styled in specific contexts; it becomes harder to change the code if we need to change the style. We will explore more of the reasons why nesting is fraught with risks later in this chapter.
Leaving aside the risks of nesting for the moment, we can use the same basic principle of nesting when using PostCSS—for this, we need to use the postcss-nesting
plugin by Jonathan Neal, which is available from https://github.com/jonathantneal/postcss-nesting. To give you a flavor of what nesting looks like in PostCSS, take a look at this screenshot—this is an online playground provided by the author for trialing nested statements, where we can see the results automatically on the right:
The key line is on the left, fifth from the bottom: the postcss-nesting
plugin uses @nest &
as the placeholder for nesting code.
To help illustrate how the postcss-nesting
plugin works, we will use it to create a somewhat unique navigation system. Our navigation will use a mix of jQuery and CSS to style and flip some demo pages, with the animation effects provided by CSS3 styling. Intrigued? Let's dive in and take a look.