What are CSS Media Queries?

CSS Media queries are snippets of code web developers use for building responsive websites. They work by triggering certain conditions based on the MEDIA used to access the web page (see what I did there?). For example, we would code one set of conditions for a desktop, and use media queries trigger different conditions for different sized browsers or devices, such as phones and iPads. The conditions are often placed within a style.css sheet.

CSS Media Queries Examples

For me, it's easier to imagine CSS media queries as if they're if - then statements that modify the rule(s) above them. For example, let's say we want to build a box that spans the entire webpage left to right. We might first build a box like this:

<div class="container">pretend the image is here</div>

.container { Width: 1920px; }

We know that one iPad resolution is 768x1024. Our general if-then statement could look like this:

.container { width: 1920px; }

@media only screen and (max-width: 1024) { .container { width: 1024px; } }

Pretty simple, right?

Now, you can add a query for a mobile phone. If you check the Chrome Developer Tools, you'll see that the iPhone 6/7/8 Plus is 414x736.

.container { width: 1920px; }

@media only screen and (max-width: 1024) { .container { width: 1024px; } }

@media only screen and (max-width: 736) { .container { width: 736px; } }

Up until now, I've been labeling these changes by devices. Most of the time developers don't think in device types, rather, they think in breakpoints. This is because a) websites today aren't created for each device and b) media queries are used to make sure the website looks good regardless of device or desktop browser size. You see, the responsiveness isn't tied to the device, rather, it's tied to the resolution. It just happens that certain popular devices are given priority in code and are used as a shortcut for developers to minimize the time they need to build a website.

Now, examples of how CSS media queries are endless. And there are already more than enough websites dedicated to tutorials and in-depth demonstrations of their uses. I just wanted to create a short answer to a big question that's geared towards people who aren't necessarily developers but want to better understand what a responsive website is and how CSS Media Queries make them possible.