CSS Media Queries enable developers to apply custom CSS styles based on device characteristics—such as screen viewport width (max-width, min-width), device orientation (portrait/landscape), and user OS preferences (light/dark mode).
Media queries wrap conditional CSS rulesets inside @media blocks:
/* Base styles (Mobile First) */
.card-grid {
display: grid;
grid-template-columns: 1fr; /* 1 column on mobile screens */
}
/* Tablet Breakpoint (768px and up) */
@media (min-width: 768px) {
.card-grid {
grid-template-columns: repeat(2, 1fr);
}
}
/* Desktop Breakpoint (1024px and up) */
@media (min-width: 1024px) {
.card-grid {
grid-template-columns: repeat(4, 1fr);
}
}
/* Dark Mode Preference Media Query */
@media (prefers-color-scheme: dark) {
body { background-color: #0f172a; color: #f8fafc; }
}
Common responsive breakpoint guidelines:
< 640px (Default base styles).min-width: 640px to 768px.min-width: 1024px.min-width: 1280px+.flowchart TD
A["Base Mobile Styles (< 640px)"] --> B["@media (min-width: 768px) -> Tablet Grid Layout"]
B --> C["@media (min-width: 1024px) -> Desktop Multi-Column Dashboard"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Media Queries Example</title>
<style>
.responsive-box {
background-color: #1e293b;
padding: 1.5rem;
border-radius: 8px;
border: 2px solid #334155;
text-align: center;
}
/* Change border color on tablet/desktop viewports */
@media (min-width: 768px) {
.responsive-box {
border-color: #38bdf8;
padding: 3rem;
}
}
</style>
</head>
<body style="background-color: #0f172a; color: #f8fafc; font-family: system-ui, sans-serif; padding: 1rem;">
<div class="responsive-box">
<h2>Adaptive Media Query Box</h2>
<p>Resize your browser window past 768px to see padding and border color update!</p>
</div>
</body>
</html>
@media (min-width: ...) breakpoints to expand layouts for larger screens.<meta name="viewport"> in HTML <head>: Without viewport metadata, mobile devices ignore CSS media queries.@media (prefers-color-scheme: dark) and @media (prefers-reduced-motion: reduce) to support system user preferences.Write a mobile-first CSS media query @media (min-width: 768px) that changes a .sidebar display from none to block!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.