RWD Media Queries
Media Queries are a fundamental part of Responsive Web Design (RWD). They allow you to apply CSS rules based on the characteristics of the user's device, such as screen size, resolution, orientation, or aspect ratio. By using media queries, you can create designs that adapt seamlessly to different environments.
Key Topics
Media Query Syntax
A media query consists of a media type (e.g., screen
) and conditions such as width, orientation, or resolution. Here’s the basic syntax:
@media media-type and (condition) {
CSS rules;
}
Using Breakpoints
Breakpoints define the screen sizes at which the design should change. Common breakpoints include:
- Small Devices:
max-width: 600px
- Tablets:
min-width: 601px
andmax-width: 1024px
- Desktops:
min-width: 1025px
Examples of Media Queries
This example demonstrates the use of media queries to adjust a layout for different screen sizes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Media Query Example</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.container {
background-color: #F0F0F0;
padding: 20px;
text-align: center;
}
.box {
background-color: #007BFF;
color: white;
padding: 20px;
margin: 10px auto;
width: 80%;
}
@media (max-width: 600px) {
.box {
background-color: #28A745;
width: 100%;
}
}
@media (min-width: 601px) and (max-width: 1024px) {
.box {
background-color: #FFC107;
width: 60%;
}
}
@media (min-width: 1025px) {
.box {
background-color: #DC3545;
width: 40%;
}
}
</style>
</head>
<body>
<div class="container">
<h1>Media Query Example</h1>
<div class="box">This box changes based on the screen size.</div>
</div>
</body>
</html>
Explanation: The box changes its width and background color based on the screen size, providing a responsive design.
Key Takeaways
- Media Queries: Essential for tailoring styles to different devices and screen sizes.
- Breakpoints: Define thresholds at which the layout changes for specific devices.
- Responsive Design: Ensures that websites are adaptable and functional on all devices.