Skip to main content

CSS Media Queries

Media queries are a powerful tool for creating responsive web designs that adapt to different devices and screen sizes. In this tutorial, you will learn how to use CSS media queries to ensure your website looks great on various devices, with sample code and simple explanations.

Basic Media Query Syntax

A media query consists of a media type and one or more expressions that check for specific conditions. The most common media type is screen, used for computer screens, tablets, and smartphones.

Example:

CSS
@media screen and (min-width: 768px) {
/* CSS styles for screens with a minimum width of 768 pixels */
}

Mobile-First Approach

A mobile-first approach means designing your website for smaller screens first and then progressively enhancing it for larger screens using media queries.

Example:

CSS
/* Base CSS styles for mobile devices */
body {
font-size: 16px;
}

/* Media query for tablets and larger devices */
@media screen and (min-width: 768px) {
body {
font-size: 18px;
}
}

/* Media query for desktop devices */
@media screen and (min-width: 1024px) {
body {
font-size: 20px;
}
}

Orientation and Resolution

Media queries can also target specific device orientations (portrait or landscape) and resolutions.

Example:

CSS
/* Portrait orientation */
@media screen and (orientation: portrait) {
/* CSS styles for portrait orientation */
}

/* High-resolution devices */
@media screen and (min-resolution: 2dppx) {
/* CSS styles for high-resolution devices */
}

Conclusion

By using CSS media queries, you can create responsive web designs that adapt to different devices and screen sizes. This ensures your website looks great and functions well across a variety of platforms, providing an optimal user experience for all visitors.