@supports
Shines Brightest on Dependent Styles
Feature queries via the @supports
CSS at-rule provide syntax to conditionally apply a set of style declarations when a
given feature is supported. It’s common to see web developers test and immediately apply
a newer CSS property:
@supports(display: grid) {
main { display: grid; }
}
But considering that browsers ignore CSS that they don’t understand, such applications of feature queries can be redundant and unnecessary.
Where feature queries really shine, however, is in preventing dependent styles from being applied. Feature queries are exceptionally suited to applying properties browsers do understand, but that are only appropriate when a more advanced property is available.
For a recent example, I started experimenting with CSS Shapes on a floated image of a Raspberry Pi on my professional website (Save a visit to the website itself and see the figure).
I did not use a feature query on
the shape-outside
property itself.
Instead, I used a feature query to prevent applying two other, more well supported features: justified text and hyphenation. The code looks like this:
@supports (shape-outside: polygon(0px 0px, 0% 0%)) {
#about p {
hyphens: auto;
text-align: justify;
}
}
I don’t want to use hyphens or text justification in the absence of the custom shape I drew around the Pi image. Their purpose is only to help the text better conform to the CSS shape and the image content. In the absence of CSS shapes support, a plain old rectangular float appears. And that’s fine. But there’s no need to bring hyphens or justification to that party, which will only further intensify the boxiness of that older-school design.
A couple of notes here to close out the post:
-
@supports
rules require not just the property but also a valid value. The valuepolygon()
is not valid by itself, so I passed in some coordinates as zero values (with units, which is poor form). Consult the MDN documentation onshape-outside
. - I highly recommend the Firefox CSS Shapes Editor, even though it feels to me like bizarro world using a WYSIWYG interface on newer CSS properties. The coordinates it generates are responsive, too, which is awesome.
- I’m forever admonishing my students not to use justification. That is still the case
for long passages of text. Run a ragged right-edge. It occurs to me that it might be wise
to also check for
hyphens
support before applying justified text, although browser hyphenation itself is still a big work in progress.