CSS Media Queries
By Tony 9.6.2024
Although we already covered a lot in this course, we haven't introduced a huge aspect of CSS: responsive design. Responsive design makes the website "responsive", so it behaves a certain way on wide screens, like computers, and behaves another on narrow screens, like phones and tablets, so it looks good on all devices. This is very important because more and more people are visiting websites using their phones, so if you only design your website to look good on computers, it will break when displaying on phones. Today, we'll learn how to prevent that using media queries.
.element {
width: 600px;
background-color: blue;
}
@media (max-width: 600px) {
.element {
width: 200px;
background-color: green;
}
}
In this example, we set the element's default width to 600 pixels and gave it a blue background. Following that is the @media rule. This is called a media query, and it gives elements certain styles only when the condition in the parentheses is met. It's a little bit like pseudo classes, but specifically for giving different styles on different devices or widths. In this example, the condition in the parentheses is max-width: 600px, meaning that the styles within the media query only apply to the elements when the screen's width is smaller than 600 pixels. When this condition is not met (screen wider than 600px), the elements will have their default styles. Now that you've set a condition, you can start giving elements styles. A media query is basically like a tiny CSS file by itself, you can use selectors just like normal inside media queries, and everything works the same. In this example, we set the element's width to 100 pixels and background to green using the .element selector in the media query.
As you can see in the playground above, if you zoom in (or zoom out depending on your screen size), you can see that at a certain point, the element's background turns green and becomes narrower. This is media query at work! Note that you can have multiple selectors and styles within a single media query, and you can have several media queries in a single CSS file. For example, you have a media query that only triggers when the screen width is smaller than 800 pixels, and you have another query that triggers when the screen is less than 200px. This means that the first query, max-width: 800px, applies when the screen width is between 800px and 200px, and after the screen size is smaller than 200px, the second query overrides the first query and applies its styles.