Media queries are used in CSS to apply different styles for different devices or screen sizes. This helps create responsive web designs that look good on all devices, from desktops to smartphones.
The @media
rule is used to define media queries in CSS. It applies styles based on the result of one or more media features, such as screen width, height, orientation, etc.
<!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 - Codersmile</title>
<style>
body {
background-color: lightblue;
}
@media (max-width: 600px) {
body {
background-color: lightcoral;
}
}
</style>
</head>
<body>
<h1>Welcome to Codersmile</h1>
<p>This is an example of using media queries.</p>
</body>
</html>
In this example, the background color of the page will change to light coral if the screen width is 600 pixels or less.
Breakpoints are specific screen widths at which the layout of the webpage changes. These are used in conjunction with media queries to make the design responsive.
Here’s an example using common breakpoints:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Breakpoint Example - Codersmile</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 20px;
}
h1 {
font-size: 24px;
}
@media (max-width: 1200px) {
body {
background-color: lightgray;
}
}
@media (max-width: 992px) {
body {
background-color: lightblue;
}
h1 {
font-size: 22px;
}
}
@media (max-width: 768px) {
body {
background-color: lightgreen;
}
h1 {
font-size: 20px;
}
}
@media (max-width: 600px) {
body {
background-color: lightcoral;
}
h1 {
font-size: 18px;
}
}
</style>
</head>
<body>
<h1>Welcome to Codersmile</h1>
<p>This is an example of using media queries with breakpoints.</p>
</body>
</html>
In this example:
h1
tag will change based on the screen width.