CSS Media Query
Learn how to create responsive websites that automatically adapt to mobile, tablet and desktop screen sizes using CSS Media Queries.
What is CSS Media Query?
CSS Media Query is a CSS technique used to apply different styles based on the device's screen size, resolution, orientation or other conditions.
Media Queries are one of the most important parts of responsive web design. They allow a website to provide a better user experience across mobile phones, tablets, laptops and large desktop screens.
Media Query Syntax
The basic syntax of a CSS Media Query is:
@media (condition) {
selector {
property: value;
}
}
Common Breakpoints
Breakpoints define the screen widths where the design changes to provide a better responsive experience.
Mobile
max-width: 576pxUsed for small mobile devices.
Tablet
max-width: 768pxSuitable for tablets and small screens.
Laptop
max-width: 992pxUsed for laptop and medium screens.
Desktop
min-width: 1200pxUsed for large desktop screens.
Media Query Examples
| Device | Media Query | Purpose |
|---|---|---|
| Mobile |
@media (max-width: 576px)
|
Small screen styling |
| Tablet |
@media (max-width: 768px)
|
Tablet responsive layout |
| Laptop |
@media (max-width: 992px)
|
Medium screen layout |
| Desktop |
@media (min-width: 1200px)
|
Large screen styling |
Practical Examples
Change Background
Change the background color on mobile screens.
@media (max-width: 576px) {
body {
background: #eef2ff;
}
}
Responsive Heading
Reduce the heading size on smaller screens.
@media (max-width: 768px) {
h1 {
font-size: 36px;
}
}
Hide an Element
Hide an element on mobile devices.
@media (max-width: 576px) {
.desktop-box {
display: none;
}
}
Responsive Grid
Convert a multi-column layout into one column.
@media (max-width: 768px) {
.grid {
grid-template-columns:
1fr;
}
}
Best Practices
Always design websites with mobile responsiveness in mind.
Use flexible units such as %, rem, em, vw and fr.
Avoid using too many unnecessary breakpoints.
Test your website on real mobile and tablet devices.
Keep your Media Query CSS organized and easy to maintain.
Prefer a mobile-first approach for responsive projects.
Frequently Asked Questions
Media Query is used to apply different CSS styles according to screen size, device characteristics or other conditions.
They help websites adapt to different devices and create a better responsive user experience.
A breakpoint is a screen width where the website layout or styling changes to improve responsiveness.
Yes. Media Queries can change columns, widths, font sizes, spacing, visibility, positioning and many other CSS properties.
Build Responsive Websites
Practice CSS Media Queries by creating layouts for mobile, tablet, laptop and desktop screens.