CSS media queries are a powerful feature in CSS (Cascading Style Sheets) that allow web developers to create responsive and adaptive layouts. They enable the application of different styles based on various device characteristics, such as screen size, resolution, or orientation.
Media queries consist of a media type and one or more expressions that check for specific conditions. When these conditions are true, the corresponding styles are applied. This mechanism forms the foundation of responsive web design.
The basic syntax of a media query is as follows:
@media mediatype and (expression) {
/* CSS rules */
}
Common media types include "screen" for computer screens, "print" for printers, and "all" for all devices. Expressions typically involve device features like width, height, or orientation.
/* Default styles for mobile */
.container {
width: 100%;
}
/* Styles for screens wider than 768px */
@media screen and (min-width: 768px) {
.container {
width: 750px;
margin: 0 auto;
}
}
In this example, the container is full-width on mobile devices. For screens wider than 768px, it becomes a fixed-width centered container.
body {
font-size: 16px;
}
@media screen and (orientation: landscape) {
body {
font-size: 18px;
}
}
Here, the font size increases slightly when the device is in landscape orientation, improving readability on wider screens.
While breakpoints should be tailored to your specific design, some common ranges include:
Device | Typical Breakpoint |
---|---|
Mobile | Up to 767px |
Tablet | 768px - 1023px |
Desktop | 1024px and above |
Media queries can also target specific device features like pixel ratio for high-resolution displays:
@media screen and (min-resolution: 2dppx) {
/* Styles for high-resolution screens */
}
This query applies styles to devices with a minimum resolution of 2 dots per pixel, common in Retina displays.
CSS media queries are essential for creating flexible, responsive web designs. By mastering this technique, developers can ensure their websites look great and function well across a wide range of devices and screen sizes. Remember to combine media queries with other responsive design techniques for the best results.