CSS Media Queries

CSS Media Queries: A Beginner’s Guide

CSS media queries allow you to apply different styles to a webpage based on the conditions of the device being used to view the webpage. This can be useful for creating a responsive design that adjusts to different screen sizes and resolutions.

To create a media query, you can use the @media rule and specify the conditions that you want to apply styles to.

Here is an example of a media query that applies a different style to the body element when the screen width is less than 500 pixels:


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

You can specify multiple conditions for a media query, such as the device type, orientation, and resolution.

Here is an example of a media query that applies a different style to the body element when the screen is a handheld device in landscape orientation with a minimum width of 700 pixels:


@media screen and (orientation: landscape) and (min-width: 700px) and (max-width: 1024px) {
  body {
    background-color: blue;
  }
}

You can also use media queries to hide or show elements based on the conditions of the device.

Here is an example of a media query that hides the navigation menu when the screen width is less than 500 pixels:


@media screen and (max-width: 500px) {
  .navigation {
    display: none;
  }
}

Bootstrap is a popular front-end framework that includes a set of predefined CSS media queries for creating a responsive design. Here are the typical media queries that are used in Bootstrap:


/* Small devices (landscape phones, 576px and up) */
@media (min-width: 576px) { ... }

/* Medium devices (tablets, 768px and up) */
@media (min-width: 768px) { ... }

/* Large devices (desktops, 992px and up) */
@media (min-width: 992px) { ... }

/* Extra large devices (large desktops, 1200px and up) */
@media (min-width: 1200px) { ... }

In conclusion, CSS media queries are an essential tool for creating a responsive design that adjusts to different devices. By using the @media rule and specifying the conditions that you want to apply styles to, you can create styles that are specific to certain screen sizes, resolutions, and device types. Media queries can also be used to hide or show elements based on the conditions of the device. Bootstrap is a popular framework that includes predefined media queries to help you create a responsive design.