Media Queries in CSS

Media Queries in CSS

Media Queries in CSS

Media queries are a powerful tool in CSS that allows you to apply different styles to your webpage based on the dimensions of the viewport, or the device that the webpage is being displayed on. They can be used to create responsive designs that adapt to different screen sizes and orientations, making your website more user-friendly and accessible on a wide range of devices.

How to Use Media Queries

To use media queries, you'll need to include them in your CSS file. Here's an example of a basic media query that changes the font size of a h1 element when the viewport is less than 500 pixels wide:

@media (max-width: 500px) {
  h1 {
    font-size: 18px;
  }
}

This media query is saying that when the viewport is 500 pixels or less, the h1 element should have a font size of 18 pixels. Any styles that you include within the media query will only be applied when the media query conditions are met.

You can use media queries to target a specific range of viewport sizes or to apply styles based on the orientation of the device. For example, you can use the min-width and max-width media features to target a range of viewport sizes:

@media (min-width: 500px) and (max-width: 800px) {
  /* Styles go here */
}

Or, you can use the orientation media feature to apply styles based on whether the device is in portrait or landscape mode:

@media (orientation: portrait) {
  /* Styles go here */
}

@media (orientation: landscape) {
  /* Styles go here */
}

You can also use media queries to apply styles based on the type of device that the webpage is being displayed on. For example, you can use the print media type to apply styles specifically for when the webpage is printed:

@media print {
  /* Styles go here */
}

Or, you can use the screen media type to apply styles specifically for when the webpage is displayed on a screen:

@media screen {
  /* Styles go here */
}

Media Query Examples

Here are a few more examples of media queries that you might find useful:

Targeting tablets in landscape mode

@media (min-width: 768px) and (max-width: 1024px) and (orientation: landscape) {
  /* Styles go here */
}

Targeting phones in portrait mode

@media (max-width: 767px) and (orientation: portrait) {
  /* Styles go here */
}

Targeting high-resolution displays

@media (min-resolution: 192dpi) {
  /* Styles go here */
}

Conclusion

Media queries are a powerful tool for creating responsive designs that adapt to different screen sizes and orientations. By using media queries, you can create a single webpage that looks great on a wide range of devices, making your website more user-friendly and accessible to a larger audience.