How do media queries work in web development for responsive design, including mobile devices?
sobes.tech AI
Answer from AI
Media queries allow applying specific CSS styles depending on device characteristics or viewport size. They are used to create responsive designs that display correctly on various screens, including mobile devices, tablets, and desktops.
Main syntax of a media query:
@media <media_type> and (<expression>) {
/* CSS rules */
}
<media_type>specifies the device type the query applies to (e.g.,screen,print,all).<expression>sets the conditions under which styles are applied (e.g., width, height, screen orientation, resolution).
Popular expressions for responsive design:
min-width: Styles are applied if the viewport width is equal to or greater than the specified value.max-width: Styles are applied if the viewport width is equal to or less than the specified value.orientation: Styles depend on the screen orientation (portraitorlandscape).resolution: Styles depend on the screen resolution.
Example of using max-width for styling on mobile devices:
/* Default styles */
body {
font-size: 16px;
}
/* Styles for screens up to 768px wide (typical for mobile) */
@media screen and (max-width: 768px) {
body {
font-size: 14px;
}
.container {
padding: 10px;
}
}
Example of using min-width for styling on desktops (mobile-first approach):
/* Styles for mobile by default */
.column {
width: 100%;
}
/* Styles for screens 992px wide and above (typical for desktops) */
@media screen and (min-width: 992px) {
.column {
width: 50%;
float: left;
}
}
Combination of expressions with and, or (in media queries, or is written as a comma), and not:
@media screen and (min-width: 768px) and (max-width: 1024px) {
/* Styles only for tablets */
}
@media screen and (orientation: landscape), print {
/* Styles for landscape orientation and printing */
}
The viewport meta tag is important for proper media query functioning on mobile devices:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
width=device-widthsets the viewport width equal to the device width.initial-scale=1.0sets the initial zoom level.
Without this meta tag, many mobile browsers scale the page by default, ignoring the actual device width, which breaks responsiveness.