Media Query

Media Query

A media query consists of a media type and can contain one or more expressions, which resolve to either true or false. The result of the query is true if the specified media type matches the type of device the document is being displayed on and all expressions in the media query are true.

Media Query Basics

The simplest media query syntax looks like this:

@media media-type and (media-feature-rule) {
  /* CSS rules go here */
}

It consists of:

  • A media type, which tells the browser what kind of media this code is for (e.g. print, or screen).

  • A media expression, which is a rule, or test that must be passed for the contained CSS to be applied.

  • A set of CSS rules that will be applied if the test passes and the media type is correct.

Media types

The possible types of media you can specify are:

  • all

  • print

  • screen

The following media query will only set the body to 10pt if the page is printed. It will not apply when the page is loaded in a browser.

@media print {
  body {
    font-size: 10pt;
  }
}

Media feature rules

Width and height

The feature we tend to detect most often in order to create responsive designs is viewport width, and we can apply CSS if the viewport is above or below a certain width β€” or an exact width β€” using the min-width, max-width, and width media features.

For example, to change the body text color to blue if the viewport is exactly 600 pixels, you would use the following media query.

@media screen and (width: 600px) {
  body {
     color: blue;
  } 
}

The width (and height) media features can be used as ranges, and therefore be prefixed with min- or max- to indicate that the given value is a minimum, or a maximum. For example, to make the color blue if the viewport is 600 pixels or narrower, use max-width:

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

Orientation

One well-supported media feature is orientation, which allows us to test for portrait or landscape mode. To change the body text color if the device is in landscape orientation, use the following media query.

@media (orientation: landscape) {
  body {
    color: blue;
  }
}

Use of pointing devices

As part of the Level 4 specification, the hover media feature was introduced. This feature means you can test if the user has the ability to hover over an element, which essentially means they are using some kind of pointing device; touchscreen and keyboard navigation does not hover.

@media (hover: hover) {
  body {
    color: blue;
  }
}

Conclusion 🎊

Hope you have enjoyedπŸŽ‰ learning about Media Query🎊
Will come up with something new next timeπŸš€

Happy Learning βœ¨πŸ’«

Β