CSS Media Queries: How to use?

CSS Media Queries allow you to create responsive designs that can adapt to different screen sizes and devices. In this tutorial, we will explain how to use CSS Media Queries to create responsive designs.

What are CSS Media Queries?

CSS Media Queries are a feature in CSS that allow you to target specific devices and screen sizes. They are used to apply different styles to a website based on the device that is being used to view the website.

Media queries work by checking the dimensions of the viewport (the visible area of a web page) and applying styles based on those dimensions. You can use media queries to create different styles for devices such as smartphones, tablets, laptops, and desktops.

How to Use CSS Media Queries

To use CSS Media Queries, you need to add them to your CSS file. Here’s how to do it:

/* This is the default style */
body {
  background-color: white;
  color: black;
}

/* This style will be applied when the screen width is less than or equal to 768 pixels */
@media (max-width: 768px) {
  body {
    background-color: blue;
    color: white;
  }
}

/* This style will be applied when the screen width is greater than 768 pixels */
@media (min-width: 769px) {
  body {
    background-color: green;
    color: white;
  }
}

In the above code, we have created a default style for the body element with a white background and black text color.

We then created two media queries. The first media query targets screens with a maximum width of 768 pixels. It changes the background color to blue and the text color to white.

The second media query targets screens with a minimum width of 769 pixels. It changes the background color to green and the text color to white.

You can add as many media queries as you need, targeting different screen sizes and devices.

Common Media Query Breakpoints

While you can set media query breakpoints to target any specific screen size, there are some common breakpoints used in responsive design. Here are some examples:

  • Mobile devices: 320px, 375px, 414px
  • Tablets: 768px, 1024px
  • Laptops: 1366px, 1440px, 1600px
  • Desktops: 1920px, 2560px

Conclusion

CSS Media Queries allow you to create responsive designs that can adapt to different screen sizes and devices. By targeting specific devices and screen sizes, you can create a website that looks great on any device. Remember to use common breakpoints and test your design on different devices to ensure it looks good.

Related posts:

  1. How to use CSS Shadow Effects?
  2. How to use CSS Text Effects
  3. How to use CSS Flexbox