Welcome to the CSS MQ (Media Queries) Tutorial! In this lesson, we'll learn how to create responsive web designs using Media Queries. By the end of this lesson, you'll be able to build websites that adapt beautifully to different screen sizes 🚀
Media Queries allow us to apply different styles to our web pages based on the characteristics of the user's device, such as its width, height, orientation, resolution, and more. This way, we can make our designs more responsive and user-friendly on various devices.
Responsive design is crucial for a seamless user experience on mobile devices, tablets, and desktop computers. With Media Queries, we can achieve this without writing separate stylesheets for each device!
A basic Media Query consists of the following parts:
all, screen, print, speechmin-width, max-width, orientation, resolution, etc.and, orHere's an example of a simple Media Query that applies a different background color for screens wider than 600 pixels:
@media screen and (min-width: 600px) {
body {
background-color: lightblue;
}
}You can also nest Media Queries inside one another, making it easier to manage and organize your styles.
body {
background-color: white;
}
@media screen and (min-width: 600px) {
body {
background-color: lightblue;
}
@media screen and (min-width: 900px) {
body {
background-color: skyblue;
}
}
}Remember to put the most specific Media Query last, as the last one will be applied when multiple Media Queries match.
Let's create a responsive navigation bar with Media Queries.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Responsive Navigation Bar</title>
<style>
nav {
background-color: navy;
overflow: hidden;
}
nav a {
float: left;
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
nav a:hover {
background-color: #ddd;
}
nav a.active {
background-color: red;
}
@media screen and (max-width: 600px) {
nav a {
float: none;
width: 100%;
}
}
</style>
</head>
<body>
<nav>
<a href="#home" class="active">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
</nav>
</body>
</html>In this example, our navigation bar has three links (Home, News, Contact). When the screen width is greater than 600 pixels, the links float next to each other. But when the screen width is 600 pixels or less, the links stack on top of each other, making the navigation bar responsive.
You can use the browser's Developer Tools to resize the viewport and test your Media Queries.
What does a Media Query do?
That's it for our CSS MQ Examples lesson! Keep practicing, and soon you'll be creating beautifully responsive web designs.
Happy coding! 💻🎉