CSS media queries are a feature of CSS that allow you to apply styles conditionally based on the characteristics of the user’s device, such as screen size, resolution, orientation, or even color preferences. They are essential for creating responsive designs, ensuring websites look good and function well on a variety of devices (e.g., desktops, tablets, and smartphones).
What Are CSS Media Queries?
CSS media queries are a feature of CSS that allow you to apply styles conditionally based on the characteristics of the user’s device, such as screen size, resolution, orientation, or even color preferences. They are essential for creating responsive designs, ensuring websites look good and function well on a variety of devices (e.g., desktops, tablets, and smartphones).
Syntax
Media queries use the @media
rule, followed by a condition and a block of CSS rules that apply if the condition is true.
@media (condition) {
/* CSS rules go here */
}
Example: Basic Media Query
/* Default styles */
body {
background-color: white;
color: black;
}
/* Apply styles when the screen width is 768px or less */
@media (max-width: 768px) {
body {
background-color: black;
color: white;
}
}
Explanations:
The default styles apply when the screen width is greater than 768px.
The media query styles apply when the screen width is 768px or less.
Common Media Query Features
Screen Width and Height:
max-width
: Targets devices with a maximum width.min-width
: Targets devices with a minimum width.
Example:
@media (min-width: 600px) {
/* Styles for screens 600px and wider */
}
Device Orientation:
orientation: landscape
: Targets devices in landscape mode.orientation: portrait
: Targets devices in portrait mode.
Example:
@media (orientation: portrait) {
body {
font-size: 18px;
}
}
Resolution:
min-resolution
or max-resolution
: Targets devices based on their screen resolution.
Example:
@media (min-resolution: 300dpi) {
img {
filter: grayscale(100%);
}
}
Why Use Media Queries?
Responsive Design: Tailor your website for different devices and screen sizes.
Improved User Experience: Provide optimized layouts and styles for every user.
Future-Proof Design: Adapt your design to new devices and technologies.