Media Queries

Media queries in CSS allow you to apply different styles to a webpage based on various characteristics of the user's device, such as screen size, resolution, orientation, and more. This documentation will provide you with a comprehensive understanding of media queries along with examples for different screen sizes.

What are Media Queries?

Media queries are a feature in CSS that enable developers to apply different styles to elements based on characteristics of the device such as screen width, height, orientation, resolution, and more. They are particularly useful for creating responsive web designs that adapt to different devices and screen sizes.

Syntax

Media queries consist of a media type and one or more expressions, which are enclosed in parentheses. The expressions typically check for certain conditions such as screen width, height, or orientation. If the conditions are met, the styles within the media query are applied.

@media media-type and (expression) {
  /* Styles to apply */
}

Example

Let's consider an example where we want to apply different styles for screens with a maximum width of 600 pixels:

@media screen and (max-width: 600px) {
  body {
    background-color: lightblue;
  }
}

In this example:

  • @media screen: Specifies that the media type is screen, indicating that the styles will apply to devices with screens.

  • and (max-width: 600px): This expression checks if the maximum width of the screen is 600 pixels or less.

  • body { background-color: lightblue; }: If the condition is met, the background color of the body element will be changed to light blue.

Media Query Examples for Different Screen Sizes

  1. Small Screens (Mobile Phones)

@media screen and (max-width: 480px) {
  /* Styles for small screens */
}
  1. Medium Screens (Tablets)

@media screen and (min-width: 481px) and (max-width: 768px) {
  /* Styles for medium screens */
}
  1. Large Screens (Desktops and Laptops)

@media screen and (min-width: 769px) {
  /* Styles for large screens */
}

Conclusion

Media queries are a powerful tool for creating responsive web designs that adapt to various devices and screen sizes. By using media queries effectively, you can ensure that your website looks great and functions well across a wide range of devices. Experiment with different media query expressions and combinations to create designs that provide the best user experience for your audience.

Last updated