Media queries
Media queries are exceptionally powerful constructs that allow us to build responsive layouts based on the properties of the device on which our code is running. For example, we can change the styling of various elements based upon the width or height of the screen or the pixel density. Alternatively, we could detect various device capabilities, such as color depth, or we could determine whether we're working with a screen or a printer. In this section, however, we're going to focus on how to detect screen size and pixel density.
Media queries can be defined using CSS @import
rules, style sheet links, and @media
rules. We'll focus on the latter, since it is of the typical form.
A media query often looks as follows:
@media only screen and (max-width: 768px) and (max-resolution: 2dppx) { /* some CSS rules that apply when this query is true */ }
The syntax is fairly flexible and you can probably already guess what the preceding rule does. But let's go over how you can craft media...