@media QueriesCSS @media queries allow you to apply different styles based on the device’s characteristics, such as screen width, height, orientation, and resolution. They are the backbone of responsive web design, helping your website look great on mobiles, tablets, laptops, and desktops.
screen, print.max-width, min-width, orientation.and, not, only to combine conditions.min-width.A media query checks one or more conditions about the device or viewport. If the condition is true, the CSS rules inside the block are applied.
/* Basic media query syntax */
@media media-type and (condition) {
selector {
property: value;
}
}
Change the background color when the screen width is smaller than or equal to 600px.
/* For screens smaller than or equal to 600px */
@media screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
When the viewport width is 600px or less (small phones, narrow windows), the whole page’s background becomes light blue. On wider screens, the background uses the default color.
Use a breakpoint at 768px to switch from a stacked layout to a horizontal (flex) layout.
/* Switch to horizontal layout on wider screens */
@media screen and (min-width: 768px) {
.container {
display: flex;
flex-direction: row;
}
}
When the screen width is 768px or more (tablets in landscape, laptops), elements inside .container will be displayed in a row, creating a multi-column layout. On smaller screens, they stay stacked vertically.
You can also react to device orientation, such as portrait or landscape.
/* Increase text size in landscape orientation */
@media screen and (orientation: landscape) {
body {
font-size: 18px;
}
}
When the device is held in landscape mode, the body text becomes larger (18px), making better use of the wider screen space. In portrait mode, the default font size is used.
You can combine max-width with orientation to target very specific scenarios.
/* Small landscape screens (e.g., some phones turned sideways) */
@media screen and (max-width: 700px) and (orientation: landscape) {
.hero-text {
text-align: center;
font-size: 1.1rem;
}
}
This rule activates only when the screen is in landscape mode and the width is 700px or less. The .hero-text is centered and slightly resized to stay readable on small horizontal screens.
min-width queries.%, rem, and vw instead of fixed px wherever possible.and keyword for fine-grained control.div that has one background color for screens less than 500px and a different color for screens more than 800px using two media queries.portrait and landscape.600px.max-width and orientation to design a special layout for small landscape devices only.