Chapter 21. CSS At-Rules
For 20 chapters now, we’ve explored the properties, values, and selectors that can be combined to create CSS rules. These are what we might call normal rules or regular rules, and they’re powerful, but sometimes more is needed. Sometimes there needs to be a way to encapsulate certain styles in conditional blocks, such that styles can be applied at certain page widths or only if a given CSS feature is recognized by the browser processing the stylesheet.
These are almost invariably enclosed in at-rules, so called because they start with an at (@) symbol. You’ve seen some of these in previous chapters, such as @font-face and @counter-style, but there are still more that aren’t so tightly bound to specifics of styling. This chapter explores the three powerful at-rules @media, @container, and @supports.
Media Queries
Thanks to the mechanisms defined in HTML and CSS called media queries, you can restrict any set of styles (including entire stylesheets) to a specific medium, such as screen or print, and to a specific set of media conditions. These mechanisms allow you to define a combination of media types and conditions such as display size or color depth, to pick two examples. We’ll cover the basic form before exploring the more complex forms.
Basic Media Queries
For HTML-based stylesheets, you can impose medium restrictions through the media attribute. This works the same for both the <link> and <style> elements:
<linkrel="stylesheet"media="print"href ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access