CSS Media Queries
Media Queries in CSS allow us to change styles depending on screen size. They are the foundation of responsive web design, which ensures your website looks good on desktops, tablets, and mobiles without building separate versions.
Syntax
@media media-type and (condition) {
/* CSS rules */
}
- @media → Starts the query.
- media-type → The type of output device (commonly screen for devices, print for printing).
- condition → The rule to check (like max-width: 800px). If true → styles inside apply.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Basic Media Query - Text & Background</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
padding: 20px;
background-color: #f4f4f4;
}
.content {
background-color: lightyellow;
padding: 20px;
border-radius: 8px;
}
h1 {
text-align: center;
color: teal;
}
p {
font-size: 18px;
color: #333;
}
/* When screen is 600px or smaller */
@media screen and (max-width: 600px) {
.content {
background-color: lightgreen;
}
p {
font-size: 14px;
color: darkred;
}
h1 {
font-size: 20px;
color: darkblue;
}
}
</style>
</head>
<body>
<div class="content">
<h1>Responsive Typography & Background</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed sit amet
feugiat nunc. Proin euismod, justo a facilisis cursus, sapien erat
fermentum sapien, nec luctus nunc nisi nec lorem.
</p>
<p>
Resize the screen smaller than 600px and see how the text size, text
color, heading style, and background color change for better readability
on mobile.
</p>
</div>
</body>
</html>
Output:
Large screens (>600px):
- Page background is light gray.
- Content box is light yellow.
- Heading is teal and bigger.
- Paragraph is dark gray and medium-sized.
Small screens (≤600px):
- Page background stays light gray.
- Content box turns light green.
- Heading becomes dark blue and smaller.
- Paragraph turns dark red and smaller.