DEV Community

Liz P
Liz P

Posted on

CSS Media Queries

Media queries are extremely useful for responsive web design. Not everyone is using a desktop all the time, most of us are probably using our phones most of the time for the things we’re doing online. Using media queries is a popular technique for delivering a tailored style sheet to desktops, laptops, tablets, and mobile phones (such as iPhone and Android phones). Media queries allow us make changes to our CSS according to device sizing. And if you’ve ever been on a site on your phone and had to endlessly scroll just to see the landing page info, you know how frustrating that is.

To get started we use the @media rule-which is used to target a specified media type. The syntax looks like this:

@media (condition) {
  // CSS that we want to happen when the condition is met
}
Enter fullscreen mode Exit fullscreen mode

For example if we want the font size to change and become smaller when someone is using a mobile device instead of a desktop, we would use a media query that looks like this:

p {
  font-size: 25px;
}

@media (max-width: 375px) {
  p {
    font-size: 18px;
  }
}
Enter fullscreen mode Exit fullscreen mode

This means that once the breakpoint is reached the custom rules you’ve defined go into effect. While there are so many devices of varying sizes out there, there are commonly used breakpoints.

• 320px — 480px: Mobile devices
• 481px — 768px: iPads, Tablets
• 769px — 1024px: Small screens, laptops
• 1025px — 1200px: Desktops, large screens
• 1201px and more —  Extra large screens, TV

You can also include the type of media in the condition (likely you’ll be using screen), there are four categories:

• all — for all media types
• print — for printers
• screen — for computer screens, tablets and, smart-phones
• speech — for screen readers that “read” the page out loud

Putting all these pieces together, a finalized media query for a tablet would look like this:

.opening-paragraph {
  font-size: 25px;
}

@media screen and (max-width: 768px) {
  .opening-paragraph {
    font-size: 20px;
  }
}
Enter fullscreen mode Exit fullscreen mode

You can make specific CSS rules for pretty much anything-we can adjust the margins, padding, font size, colors, etc. They’re pretty powerful. I hope this helps a little. In the past I’ve typically used a library or framework like Bootstrap that pretty handles the responsiveness for you but if you’re using plain old CSS media queries will be your best friend. Thanks for reading!

Top comments (0)