How to Use Media Queries

At Designfox, we build custom responsive themes for each website. Responsive means the website is displayed differently based the device on which it is viewed. Some elements may appear correct regardless of viewing device while other elements need to be styled differently for different devices. Element can be styled differently for different browser widths with browser width-specific selector declarations.

First, what are selector declarations?

Selector declarations declare how an element should be displayed generally. For example, if we want to show all header 1 elements in red, we could declare the following in the stylesheet:


h1 {
color: red;
}

The result would be that all h1 elements would be colored red. But let's say that we want the h1 elements to be green when viewed on a vertical tablet or larger. We would use a browser width-specific selector declaration. Because we are being more specific, the browser width-specific declaration prevails over the general declaration.

What are browser width-specific selector declarations?

Browser width-specific selector declarations are declarations that only apply when a browser's width is within a certain range and that prevail over the general declaration. We achieve this by wrapping the global sector in a media query. Media queries are CSS3 declarations for limiting a selector's declarations to a certain media frame, whether it be screen or print, range of browser widths, device pixel ratio or otherwise.

For our example, we care about a range of browser widths. We could have h1 elements display in green at vertical tablet size and above by adding the following:


@media (min-width: 768px) {
h1 {
color: green;
}
}

The result is that on vertical tablets and above, the h1 elements are green. On narrower browser-widths, this selector doesn't apply, so the h1 is displayed in red.

What's the best practice for using browser width-specific declarations?

If we just use the code examples above, all major browsers load the general declaration even though it will be overwritten on vertical tablet and higher by the media query. Because downloading an extra declaration takes longer, it should be avoided. Here's the best practice to avoid unnecessary declarations from being downloaded:


@media (max-width: 767px) {
h1 {
color: red;
}
}
@media (min-width: 768px) {
h1 {
color; green;
}
}

The resut is that a browser with a width narrower than vertical tablet will only download the red declaration. And a browser with a width of vertical tablet or wider will only download the green declaration. In this example, the savings are nominal. But applied across an entire site, the savings accrue. And in certain circumstances, a few simple declarations can create great savings, like preventing large images from being downloaded when they won't be used.

Everyone at Designfox is an expert web developer. We use media queries all the time. Call us at (631) 673-5500 for help with your project.