Main menu

Post navigation

The PostCSS Guide to Improving Selectors and Media Queries

Recent changes to the CSS specifications have introduced quite a few interesting features. Unfortunately, some of them are still in a draft state and the ones that aren’t lack broad browser support. As usual, it will take a while for the new suggestions to be reviewed, accepted and implemented by the browsers. However, we can spare ourselves the long wait and try out some of these features already using PostCSS.

PostCSS has a variety of plugins aiming at implementing polyfills for the newest CSS features. Since the spectrum of these plugins is broad, it would be difficult to cover all of them in a single article. Instead, we will narrow our gaze to a selection of plugins that focus on adding new capabilities to selectors and media queries. Many of them will allow us to significantly improve the structure of our stylesheets while others may just add some sweet syntax sugar on top.

Rule Nesting

Let’s start with what is likely to be the most basic feature of all — and certainly familiar to every pre-processor user — nesting. The postcss-nesting plugin implements style rule nesting according to the W3C nesting module proposal.

The proposal introduces a new & nesting selector which references the parent selector. As opposed to Less or Sass, according to the specification, this selector is mandatory and must be the first basic selector in a chain of selectors to enable nesting. Any selectors which do not contain the nesting selector will be ignored. For example:

To allow inserting of the parent selector into any place in a selector (instead of just the beginning), the proposal defines an alternative syntax using the nesting at-rule @nest. We can fix the .latest & selector from the previous example in the following way:

.article {
color: #333;
@nest .latest & {
border: 1px solid red;
}
}

Which will compile into:

.article {
color: #333
}
.latest .article {
border: 1px solid red
}

The @nest syntax is also a tad more expressive then just &.

Custom Selectors

When writing CSS, we tend to write a lot of repeating selectors. This may be simple boilerplate code to select all links or any button, or a more complex selector that needs to be repeated over and over. This can introduce a lot of code duplication along with all the related problems of code maintenance. The new CSS extensions specification introduces a way to store selectors in variables and reference them from other parts of the stylesheets. Thus, a repeating selector can be defined only once and safely reused elsewhere.