OneBite.Dev - Coding blog in a bite size

use media query in css

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

In this article, we will delve into a fundamental aspect of responsive web design - the Media Query. Usually employed in CSS, it allows us to create different layout and element styles based on the characteristics of the device our site is being viewed on.

Code snippet for Media Query

Below is a simple illustration of how media queries are typically used in a CSS stylesheet:

@media (max-width: 600px) {
  body {
    background-color: lightblue;
  }
}

Code Explanation for Media Query

In this example, the @media rule is a media query in CSS that will take effect when the browser’s viewport is 600px wide or less. The (max-width: 600px) condition is the media feature that describes the specific browser condition to be met.

The CSS inside this media query is applied only when the media feature condition is true. In this case, when the browser’s viewport is 600px wide or less, the background-color of the body element is set to lightblue.

This means that if someone were to resize their browser screen or if they were viewing your site from a device that has a screen width of 600px or less, the body background color would change to light blue. Once the screen exceeds this width, the standard CSS styles will apply.

Let’s break down the media query:

  • @media: This is the media rule where you define the type of media where the CSS rules will apply.

  • (max-width: 600px): This is the media feature where you set the condition that must be met to apply the CSS rule. max-width means the rule will apply to any device with a maximum width of 600px.

  • {body {background-color: lightblue;}}: This is the actual CSS rule that will apply if the media feature condition is met.

Media queries are a powerful tool for responsive design, allowing you to ensure that your website looks and functions as intended on a variety of devices and screen sizes. Though this example is a simple one, you can apply a multitude of different styles within your media queries to accommodate varying screen sizes. But remember, as with any powerful tool, careful and considered use is essential for the best results.

css