Welcome to our deep dive into the world of CSS Media Queries! In this comprehensive tutorial, we'll explore this powerful feature that allows us to create responsive designs suitable for various devices and screen sizes.
Media Queries are a part of CSS3 that help tailor the look and feel of web pages to specific devices, screen sizes, and orientations. They're crucial for creating responsive designs that adapt to different screen sizes, ensuring your website looks great on desktops, tablets, and mobile devices.
@media (media-type and (expression)) {
/* CSS rules to be applied */
}Here, media-type can be all, print, screen, speech, etc., and expression is a condition based on the device's capabilities, like screen width, height, resolution, etc.
Let's see a simple example of a media query that applies different styles for screens wider than 600px:
@media (min-width: 600px) {
/* Styles for screens 600px and wider */
body {
font-size: 18px;
}
}Now that you have a basic understanding of media queries, let's dive deeper and explore more complex examples.
Besides the minimum width, other media query types include:
min-height: Applies styles when the viewport's minimum height is greater than the specified value.max-width: Applies styles when the viewport's maximum width is less than the specified value.max-height: Applies styles when the viewport's maximum height is less than the specified value.orientation: Applies styles based on the screen's orientation (landscape or portrait).Let's create a real-world example where we adjust the font size and layout for different screen sizes:
@media (min-width: 600px) {
body {
font-size: 18px;
}
.container {
display: flex;
justify-content: space-between;
}
.sidebar, .main-content {
width: 45%;
}
}
@media (max-width: 600px) {
body {
font-size: 16px;
}
.container {
display: block;
}
.sidebar, .main-content {
width: 100%;
}
}In this example, we have two media queries. The first one applies styles for screens wider than 600px, making the font size larger, setting a flexible layout, and adjusting the width of the sidebar and main content. The second media query adjusts the font size and layout for screens narrower than 600px, making the layout stack on top of each other.
Keep learning and experimenting with media queries to create responsive and adaptive designs! 🚀