How can I use media queries to make my layout mobile-friendly?
Asked on Sep 03, 2025
Answer
Media queries are a powerful tool in CSS that allow you to apply styles based on the characteristics of the user's device, such as its width. They are essential for creating responsive, mobile-friendly layouts.
<!-- BEGIN COPY / PASTE -->
<style>
/* Default styles for larger screens */
.container {
width: 80%;
margin: auto;
background-color: lightgray;
}
/* Media query for devices with a max width of 600px */
@media (max-width: 600px) {
.container {
width: 100%;
padding: 10px;
}
}
</style>
<div class="container">
<p>This layout adjusts based on screen size.</p>
</div>
<!-- END COPY / PASTE -->Additional Comment:
- Media queries use the "@media" rule to apply styles conditionally.
- The "max-width" condition targets devices with a width of 600px or less, typically smartphones.
- Adjust the styles inside the media query to optimize the layout for smaller screens, such as increasing padding or changing widths.
- Consider using other conditions like "min-width" or "orientation" for more specific targeting.
Recommended Links: