All About CSS Media Queries

css media queries guide
10 November 2024

Media queries are one of the most important features of CSS that allow us to apply different styles based on the properties of users' devices. Simply put, using media queries, we can define how each part of a website should be displayed on different devices. This feature helps us design websites that are fully responsive and suitable for various devices.

Let’s illustrate this subject with a simple example. Assume you have a website that needs to perform well on each device, including mobile, tablet, and desktop. By using media queries, we can determine how different components are displayed in different sizes. This provides complete control over the website's appearance.

You might think that you can achieve this by using fixed sizes, but you should know that the sizes of devices and pages are incredibly diverse and are becoming increasingly varied day by day. Media queries can absolutely help with this because they allow us to apply styles based on different characteristics such as size and resolution, device type, and even specific features like prefers-reduced-motion.

Today, responsiveness is one of the most crucial factors for user attraction and retention on a website, and this is the reason why understanding and using media queries and fully grasping them is essential. By understanding these techniques, you can ensure that your website provides users with the best possible experience.

Below is a simple example of CSS media queries that you can use in your designs.

Example of CSS Media Query


@media (max-width: 600px) {
body {
background-color: lightblue;
}
}
@media (min-width: 601px) and (max-width: 1200px) {
body {
background-color: lightcoral;
}
}
@media (min-width: 1201px) {
body {
background-color: lightgreen;
}
}

Explanation for Each Line of Code

@media (max-width: 600px)
This line indicates that specific styles will be applied to screens that have a width less than or equal to 600 pixels.

body { background-color: lightblue; }
When the above condition is met, the background color will change to lightblue.

@media (min-width: 601px) and (max-width: 1200px)
This line states that specific styles will be applied to screens with a width between 601 and 1200 pixels.

body { background-color: lightcoral; }
When the previous condition holds, the background color will change to lightcoral.

@media (min-width: 1201px)
This line indicates that styles will be applied to screens with a width greater than or equal to 1201 pixels.

body { background-color: lightgreen; }
In this case, the background color will change to lightgreen.

FAQ

?

What exactly do media queries do?

?

Can most browsers support media queries?