CSS Max-Width Media Queries
November 9, 2024 ยท AI Conversations
User
css media quiery max
Assistant
CSS media queries with the `max` keyword are commonly used to apply styles based on the maximum width of the viewport. This is helpful for creating responsive designs that adjust for different screen sizes, especially on smaller devices like tablets and smartphones.
Here's the basic syntax:
### Media Query with `max-width`
@media (max-width: 768px) {
/* Styles for devices with a viewport width of 768px or less */
body {
font-size: 14px;
}
}
### Common Breakpoints with `max-width`
Here are some commonly used breakpoints for responsive design:
/* Extra small devices (phones, less than 576px) */
@media (max-width: 575.98px) {
/* Styles for phones */
}
/* Small devices (tablets, 576px and up) */
@media (max-width: 767.98px) {
/* Styles for tablets */
}
/* Medium devices (desktops, 768px and up) */
@media (max-width: 991.98px) {
/* Styles for small desktops */
}
/* Large devices (large desktops, 992px and up) */
@media (max-width: 1199.98px) {
/* Styles for large desktops */
}
/* Extra large devices (very large desktops, 1200px and up) */
@media (max-width: 1399.98px) {
/* Styles for very large desktops */
}
### Example: Responsive Navbar
Here's an example of a responsive navbar that collapses on smaller screens:
/* Styles for desktop */
.navbar {
display: flex;
justify-content: space-between;
padding: 20px;
}
/* Styles for mobile devices */
@media (max-width: 768px) {
.navbar {
flex-direction: column;
align-items: center;
}
.navbar a {
display: block;
margin: 10px 0;
}
}
### Explanation
– **`max-width`**: Targets screens that are **equal to or less than** the specified width.
– **`.navbar` styles** will change based on screen size, making it responsive.
These media queries are especially useful for ensuring that your layout adapts well to various screen sizes, improving user experience across devices.