Media Queries and Container Queries

Media queries are a powerful tool in CSS that allow you to apply different styles based on specific conditions, such as screen size, orientation, resolution, and more. They are essential for creating responsive web designs that adapt to various devices and screen sizes.

Basic Structure of a Media Query

A media query consists of two main parts:

  1. Media type: Specifies the type of media the query targets (e.g., screen, print).
  2. Conditions: Defines the conditions under which the styles should be applied.

Common Conditions

  • width and height: Specify the viewport width and height.
  • min-width and max-width: Set minimum and maximum width values.
  • min-height and max-height: Set minimum and maximum height values.
  • orientation: Specify the orientation of the device (portrait or landscape).
  • resolution: Specify the screen resolution.

Example:

@media only screen and (max-width: 600px) {

  /* Styles for screens narrower than 600px */

  .header {

    text-align: center;

  }

  .nav {

    display: none;

  }

}

Container Queries

Container queries are a proposed CSS feature that would allow you to apply styles based on the width or height of a specific container element, rather than the viewport. This can be useful for creating more responsive and adaptable layouts.

Note: Container queries are not yet fully supported by all browsers, but there are polyfills and experimental features available to use them today.

Example (using a polyfill):

.container {

  container-type: inline-size; /* Set the container type to inline-size */

}

@container (min-width: 600px) {

  .container {

    /* Styles for containers wider than 600px */

  }

}

Using Media Queries and Container Queries Together

You can combine media queries and container queries to create even more flexible and responsive layouts. For example, you could use a media query to target different screen sizes, and then use container queries to adjust the layout within specific containers based on their width.

By effectively using media queries and container queries, you can create responsive web designs that adapt seamlessly to various devices and screen sizes, providing a great user experience for all users.

The element | Writing HTML Markup
The meta tag and Media Queries | Media Queries and Container Queries

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?