CSS Media Queries

CSS media queries are a vital part of responsive web design. They allow us to apply specific styles only when certain conditions are met, usually the width of the viewport. This is very useful as it allows us to have a different layout for desktop screens than for mobile devices, for example.

If you are going to start making responsive websites then it is very important that you learn how to use CSS media queries. This will give you the flexibility and control that you need to be able to make a site that works for all types of devices. It will also help you to avoid having the same layout for both desktop and mobile devices as this can be very confusing for your visitors.

Media queries were first introduced in CSS in 1998 but gained popularity after Ethan Marcotte’s 2010 article on Responsive Web Design. These simple snippets of code have transformed the way that we make websites and have helped to ensure that all sites look great across a wide range of screen sizes and devices.

A media query starts with the @media rule that wraps the elements of your website. Inside this you can add a number of conditional statements that determine when and how to apply the style rules contained within it. The most common condition is the width of the viewport, as this is one of the main factors in determining how much can be displayed on a device. However, you can also use other conditions such as the type of device or whether it is in portrait or landscape mode.

The @media rule is then followed by the media features that you want to test for. These can be grouped together using the and, not and only logical operators. This is the best way to create a complex media query and it is worth learning the syntax for each of them in order to understand how they work.

There are a variety of media features to choose from, although some have been deprecated in the latest version of CSS (CSS3) and should be avoided. The most commonly used media features are print, screen and speech.

When writing a media query you need to decide how many breakpoints you want it to have. This will be determined by how many media features you are testing for and how much flexibility you want to have in your responsive layouts. For example, you may want to have a layout that looks good on both tablets and smartphones or you might just want a basic responsive layout that will display correctly on desktop computers and all other devices.

When defining a media query you will need to specify a width in px. The browser will then determine the maximum screen size it supports and will apply the appropriate styles based on that information. You can also use a float value to set the pixel width that you want your learn css media queries to target.