CSS Media Queries

CSS Media Queries

The Media Query in CSS is used to create responsive web pages. It means that the view of the page depends on the size of the screen on which the web page is being viewed.

Media Queries has made possible to define different style rules for different media types or for different screen types.

Media Queries can be used to check many things like:-

  1. width and height of the viewport
  2. width and height of the device
  3. orientation (is the tablet/phone in landscape or portrait mode?)
  4. resolution

Syntax of Media Query

The syntax of media query consists of a media type and can contain one or more expressions, which resolve to either true or false.

@media not|only mediatype and (expressions) {
  CSS-Code;
}

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. When a media query is true, the corresponding style sheet or style rules are applied.

The media type refers to the category of media for the device. The different media types include all, print, screen and speech.

  1. all - works for all devices
  2. print - works for devices where the media is in print preview mode
  3. screen - works for devices with screens
  4. speech - works for devices like screen readers where the content is read out loud to the user

Some Media Queries Example

The following example below changes the background-color to green if the viewport is 480 pixels wide or wider (if the viewport is less than 480 pixels, the background-color will be red):

<style>
body {
  background-color: rgb(189, 29, 56);
}
@media screen and (min-width: 480px) {
  body {
    background-color: rgb(25, 154, 25);
  }
}
</style>
</head>
<body>
<h1>Media Query in CSS</h1>
<p>The media query will only apply if the media type is screen and the viewport is 480px wide or wider.</p>
</body>

The below example changes the background-color to blue if the viewport is 992 px or wider and the background-color changes to red if the viewport is 600px or wider. By default, the background-color is set to yellow.

<style>
body {
  background-color: yellow;
  color: black;
}
@media screen and (max-width: 992px) {
  body {
    background-color: blue;
    color: white;
  }
}
@media screen and (max-width: 600px) {
  body {
    background-color: red;
    color: white;
  }
}
</style>
</head>
<body>
<h1>CSS Media Query</h1>
<p>By default, the background color of the document is "yellow". 
    If the screen size is 992px or less, the color will change to "blue". 
    If it is 600px or less, it will change to "red".</p>
</body>

Hope you liked this short article on Media Queries. Happy Learning 😉!!!

If you enjoyed reading this article, like, share and comment your valuable feedback ✌.