Table of Contents
Media queries are a powerful feature of CSS that allow web developers to create responsive websites. They enable content to adapt based on the device’s screen size, resolution, or capabilities. This is especially useful for hiding or showing content depending on whether a user is on a desktop, tablet, or mobile device.
What Are Media Queries?
Media queries are conditional CSS rules that apply styles only when certain conditions are met. For example, you can specify styles that only apply when the screen width is less than 768 pixels, typically the size of a mobile device.
Using Media Queries to Hide or Show Content
To control content visibility, you can use media queries to add or remove CSS classes or styles. This allows you to hide elements on specific devices or show them only when certain conditions are true.
Example: Hiding Content on Mobile Devices
Suppose you want to hide a sidebar on mobile devices. You can add a CSS class to the sidebar and then define a media query to hide it on small screens:
/* CSS to hide sidebar on screens smaller than 768px */
@media (max-width: 768px) {
.sidebar {
display: none;
}
}
Example: Showing Content Only on Mobile
Similarly, to display content only on mobile devices, you can hide it on larger screens:
/* CSS to show element only on small screens */
@media (max-width: 768px) {
.mobile-only {
display: block;
}
}
@media (min-width: 769px) {
.mobile-only {
display: none;
}
}
Best Practices for Media Queries
- Use relative units like em or rem for flexible design.
- Test your site on multiple devices and screen sizes.
- Combine media queries with accessible design principles.
- Keep your CSS organized and avoid excessive overrides.
By effectively using media queries, you can create websites that are adaptable and user-friendly across all devices. This enhances user experience and ensures your content is accessible to everyone.