In the past, the creation of websites that adapted well to different screen sizes was a luxury that website owners had to request from a developer. However, the uptick in the use of smartphones and tablets has now made responsive design a necessity in the world of software development.

Using media queries is hands down the best way to ensure that your website/web app appears exactly how you want it to on every device.

Understanding Responsive Design

In a nutshell, responsive design deals with using HTML/CSS to create a website/web app layout that adapts to various screen sizes. In HTML/CSS there are a few different ways to achieve responsiveness in a website design:

Using rem and em units instead of pixels (px) Setting the viewport/scale of each webpage Using media queries

What Are Media Queries?

A media query is a feature of CSS that was released in the CSS3 version. With the introduction of this new feature users of CSS gain the ability to adjust the display of a webpage based on a device/screen height, width, and orientation (landscape or portrait mode).

Read more: The Essential CSS3 Properties Cheat Sheet

Media queries provide a framework for creating code once and using it multiple times throughout your program. This might not seem so helpful if you’re developing a website with only three web pages, but if you’re working for a company with hundreds of different web pages—this will prove to be a massive time saver.

Using Media Queries

There are several different things that you need to take into account when using media queries: structure, placement, range, and linking.

The Structure of Media Queries

Example of a Media Query Structure

The general structure of a media query includes:

The @media keyword The not/only keyword A media-type (which can be either screen, print, or speech) The keyword “and” A unique expression enclosed in parentheses CSS code enclosed in a pair of open and close curly braces.

Example of a Media Query With the Only Keyword

The example above applies CSS styling (specifically a blue background color) to only device screens that have a width of 450px and under—so basically smartphones. The “only” keyword can be replaced with the “not” keyword and then CSS styling in the media query above would only apply to print and speech.

However, by default, a general media query declaration applies to all three media types so there is no need to specify a media type unless the aim is to exclude one or more of them.

Default Media Query Example

The Placement of Media Queries

A media query is a CSS property; it can, therefore, only be used within the styling language. There are three different ways to include CSS in your code; however, only two of those methods provide a practical way to include media queries in your programs—internal or external CSS.

The internal method includes adding the