Introduction
In today’s mobile-first world, making websites responsive is essential. That’s where CSS media queries come in. Today, I learned how to use media queries in CSS, and in this blog, I’ll share the basics and how you can use them to make your websites look great on all screen sizes.
What is a Media Query?
A media query is a CSS technique used to apply styles based on the device's characteristics, like screen width, height, orientation, or resolution. It helps make websites responsive.
Syntax of a Media Query
@media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
@media is the rule.
only screen targets screen devices.
(max-width: 600px) means it will apply when the screen is 600px or less.
Inside the curly braces, you write the CSS rules that should apply.
Common Media Query Breakpoints
/* Small devices (phones) */
@media (max-width: 600px) { ... }
/* Tablets */
@media (min-width: 601px) and (max-width: 992px) { ... }
/* Laptops */
@media (min-width: 993px) and (max-width: 1200px) { ... }
/* Desktops */
@media (min-width: 1201px) { ... }
These are just examples. You can set custom breakpoints based on your design needs.
Why Media Queries Matter
Improves user experience across different devices
Helps build mobile-friendly websites
Allows you to customize layouts for different screen sizes
My Practice Example
/* Default style */
p {
font-size: 16px;
color: black;
}
/* For mobile screens */
@media (max-width: 600px) {
p {
font-size: 14px;
color: blue;
}
}
This changes the paragraph text size and color on smaller screens.
Final Thoughts
Learning media queries has helped me understand how to build responsive designs. It’s a simple but powerful tool in CSS that every web developer should master.
Top comments (0)