Media queries (for responsive design)
Media query in CSS is a powerful tool that allows you to apply styles to your web page based on the characteristics of the device or viewport rendering the page.
This is essential for creating responsive designs, which adjust the layout and appearance of content to suit different screen sizes, orientations, resolutions, and other device features.
How Media Queries Work
Media queries evaluate certain conditions, such as the width of the viewport, and then apply specific CSS rules if those conditions are met. These conditions are called media features.
Common Media Features
width
andheight
: Viewport's width and height.device-width
anddevice-height
: Device's screen width and height.orientation
: Device's orientation (portrait or landscape).
Syntax
@media media-type (media-feature) {
/* CSS rules */
}
media-type: This specifies the type of device you’re targeting (e.g., screen, print, all).
media-feature: This is the condition that must be true for the styles within the media query to apply.
Examples:
/* Default styles for all devices */
body {
font-size: 16px;
background-color: white;
}
/* Styles for screens with a maximum width of 600px */
@media screen and (max-width: 600px) {
body {
font-size: 14px;
background-color: lightgray;
}
}
/* the background color and font size will change when the
viewport width is 600px or less. */
/* Targeting landscape orientation */
@media screen and (orientation: landscape) {
body {
background-color: lightblue;
}
}
/* Combining Multiple Conditions */
@media screen and (min-width: 600px) and (max-width: 1200px) {
body {
font-size: 18px;
background-color: lightyellow;
}
}
/* the styles apply only when the screen width is between 600px and 1200px. */