OneBite.Dev - Coding blog in a bite size

use media queries in css

Code snippet for how to use media queries in css with sample and detail explanation

Media queries in CSS are a powerful feature that can help you create responsive websites. They allow you to apply different styles for different screen sizes and devices.

Code snippet: Basic Media Query in CSS

The following code sets the background color to green when the viewport is 600px wide or less:

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

Code Explanation for Basic Media Query in CSS

This code snippet is a simple example of a media query in CSS. The @media rule is used to include a block of CSS properties only if a certain condition is true.

The only screen part of the query means the CSS within this query will only apply to screen devices. It could be left out, the code would still work, but it’s considered good practice to include it to prevent older browsers that don’t support media queries with media types other than ‘screen’ from applying the contained CSS.

Next, we have (max-width: 600px), this is called a media feature. In this case, it’s set up to apply the styles to screens with a maximum width of 600px. Meaning if the browser window is 600 pixels wide or less, the CSS within this block will be used.

body { background-color: lightgreen; } is the CSS rule that’s being applied when this condition is true. The rule is saying, when the viewport width is 600px or less, make the background color of the body element light green.

You can replace the body selector with any CSS selector, and background-color: lightgreen; with any CSS property to suit the needs of your site. This code is just a simple example that highlights how the basic structure of a media query operates.

When the media query becomes false (meaning, as soon as the viewport grows larger than 600px), the default CSS is applied again.

Media queries are incredibly versatile, and can test for many things, such as:

  • Width and height of the viewport
  • Width and height of the device
  • Orientation (is the tablet/phone in landscape or portrait mode?)
  • Resolution

By using media queries, you can tailor your site’s design to your user’s device and its display.

css