CSS Media Queries is a technique used in CSS that enables web developers to create responsive web designs tailored to different media types and conditions. Simply put, media queries allow us to apply different CSS styles based on specific characteristics of the user's device, such as screen width, resolution, and device type.
Usage
Media queries are primarily used through the @media rule, which can be defined directly in CSS or linked via the media attribute in the <link> tag to external style sheets. Basic syntax is as follows:
css@media (condition) { /* CSS rules applied when the condition is met */ }
Example
Suppose we want to design a webpage that displays different layouts on small-screen devices (e.g., mobile phones) and large-screen devices (e.g., desktop computers).
css/* Basic styles for all devices */ body { background-color: lightblue; } /* For devices with screen width less than 600px */ @media (max-width: 600px) { body { background-color: lightgreen; } } /* For devices with screen width between 600px and 1200px */ @media (min-width: 600px) and (max-width: 1200px) { body { background-color: lightyellow; } } /* For devices with screen width greater than 1200px */ @media (min-width: 1200px) { body { background-color: lightcoral; } }
In the above example, the background color changes based on different screen widths. This way, regardless of whether the user is browsing on a mobile phone, tablet, or desktop computer, they receive an appropriate visual experience.
Application Scenarios
Media queries are widely used in responsive web design to help developers achieve compatibility across multiple devices and improve user browsing experience. In addition to adjusting styles based on screen width, media queries can customize styles based on other characteristics, such as device orientation (portrait or landscape) and resolution.
By properly utilizing CSS media queries, websites can significantly enhance their flexibility and user satisfaction.