Container Queries: Meet the new way to make responsive magic

Container Queries: Meet the new way to make responsive magic

As new technologies transform web development rapidly, staying up to date with the latest technologies and best practices is crucial. One of the most exciting additions to the CSS arsenal is the introduction of CSS container queries. Container queries promise to revolutionize the way we create responsive web layouts, offering more granular control over the layout of elements within containers. 

For years, CSS media queries have been the go-to tool for creating responsive web layouts. They allow us to modify styling based on characteristics of the user’s device, like width, resolution, and orientation. However, media queries have a limitation – they can only access global information about the environment. What if we could query the properties of a specific element on the page instead?

In this blog post, we will dive deep into CSS container queries, exploring what they are, why they matter, and how to use them effectively in your web projects.

Introducing Container Queries

Container queries, a relatively new feature in CSS, allow you to adapt your CSS styles based on the size of the container element, rather than the size of the viewport. This is in contrast to media queries, which apply CSS rules based on the size of the viewport.

Container queries are more specific than media queries, as they allow you to target specific elements within a container, rather than applying rules to the entire page.

This is a significant development in responsive web development, as it gives you more control over how your elements are displayed based on the context in which they appear.

Some key aspects:

  • They target a container, rather than the global viewport.
  • We can check the container’s size, aspect ratio, or other characteristics.
  • Styles are applied based on the container’s state, not the viewport.

Why Are CSS Container Queries Important?

To grasp the importance of CSS container queries, it’s crucial to first compare them to traditional media queries, which have long been the cornerstone of responsive web development.

Traditional Media Queries:

Traditional media queries have served web developers well for years. They allow us to adapt our web layouts to different viewport sizes or device characteristics. For example, with media queries, you can change the layout of a webpage when the viewport width falls below a certain threshold or adjust font sizes based on the device’s screen size.

However, traditional media queries have a limitation: they are based on the viewport, not the content within the page. This means that while media queries can help us create layouts that respond to the overall screen size, they do not account for the content’s size and structure within a container. This limitation often leads to suboptimal or inconsistent user experiences.

CSS Container Queries:

CSS container queries, on the other hand, introduce a paradigm shift in responsive web development. They enable developers to adapt the layout and styling of elements based on the size of their containing element. In other words, instead of focusing solely on the viewport size, container queries allow us to respond to the actual content within containers.

This granular level of control is a game-changer. With container queries, you can ensure that your layout adapts seamlessly to the content it holds. For example, if you have a card component with varying amounts of text, you can use container queries to adjust the card’s size, font size, or layout based on the content it contains.

Advantages over media queries:

More granular control: Container queries allow you to target specific elements within a container, whereas media queries apply rules to the entire page. This gives you more granular control over how your elements are displayed.

More responsive layouts: Container queries can be used to create more responsive layouts, as they allow you to adapt your CSS styles based on the size of the container element. This is especially useful for creating responsive layouts for sidebars, footers, and other elements that may appear in different contexts.

More modular CSS: Container queries can help you write more modular CSS code, as they allow you to separate the styles for a component from the styles for its container. This can make your code easier to maintain and reuse.

Getting Started with Container Queries

To start using CSS container queries in your projects, you need to enable them in your CSS code. However, it’s essential to be aware that, browser support for container queries is still in its early stages. Therefore, using container queries may require some workarounds and feature detection. Here’s how to get started:

In order to use container queries, you must first declare a containment context on an element, letting the browser know that you may want to query the container’s dimensions at a later time.

We will go into greater detail on the containment context in the later section of this post.

Container queries are defined using the @container rule. The syntax for container queries is as follows:

Syntax

@container (<query>) {
 /* CSS rules */
}

Usage:

To enable container queries in your CSS, you’ll need to add a CSS at-rule called @container. This rule defines the conditions under which the content within a container should respond. The <query> in the above syntax is a size query, which specifies the size of the container element that you want to target. Size queries can be specified using either min-width or max-width keywords. For example, the following container query will apply the CSS rules to the element only if its container is at least 300px wide:

@container (min-width: 300px) {
  /* CSS rules */
}

In this example, the contained content will respond when the container reaches a minimum width of 300px. You can define various conditions, such as min-width, max-width, and more, to control how the content adapts.

Usage examples

Here are a few examples of how container queries can be used:

Responsive sidebar: You can use container queries to create a responsive sidebar that collapses to a smaller width when the container is narrower than 768px.

@container (max-width: 768px) {
  .sidebar {
    width: 20%;
  }
}

Responsive footer: You can use container queries to create a responsive footer that changes its layout based on the width of the container.

@container (min-width: 480px) {
  .footer {
    flex-direction: row;
  }
}
@container (max-width: 480px) {
  .footer {
    flex-direction: column;
  }
}

Responsive card: You can use container queries to create a responsive card that changes its layout based on the width of the container.

@container (max-width: 480px) {
  .card {
    flex-direction: column;
  }
}

Containment context

A containment context is a region of a web page in which layout and styling are contained. This means that elements within a containment context cannot be affected by elements outside of the containment context.

Containment contexts are used to create isolated environments for layout and styling. This can be useful for creating responsive layouts, modular CSS, and accessible web pages.

Properties

The container-name and container-type properties are used to create and define containment contexts.

The container-name property specifies the name of the containment context. The container-type property specifies the type of containment context.

There are two types of containment contexts:

Size containment: Size containment prevents elements within the containment context from being affected by the size of the elements outside of the containment context.

Inline-size containment: Inline-size containment prevents elements within the containment context from being affected by the inline size of the elements outside of the containment context.

Usage example

<div class="container">
  <div class="sidebar"></div>
  <div class="main-content"></div>
</div>
.container {
  container-type: size;
  container-name: my-container;
}

@container (my-container) (min-width: 768px) {
  .sidebar {
    width: 25%;
  }

  .main-content {
    width: 75%;
  }
}

@container (my-container) (max-width: 768px) {
  .sidebar {
    width: 50%;
  }

  .main-content {
    width: 50%;
  }
}

This example code will create a containment context for the element with the class container. The container-type property is set to size, which means that elements within the containment context cannot be affected by the size of the elements outside of the containment context. The container-name property is set to my-container, which gives the containment context a name.

The two @container rules will apply different CSS styles to the element within the containment context based on the width of the containment context. If the width of the containment context is at least 768px, the sidebar will be 25% wide and the main content will be 75% wide. If the width of the containment context is less than 768px, the sidebar and the main content will both be 50% wide.

This example shows how container queries can be used to create responsive layouts that adapt to different screen sizes. By targeting the containment context instead of the viewport, we can ensure that the layout of the page remains consistent, even if the width of the viewport changes.

Browser support

Container queries are a relatively new feature, and they are not yet supported by all browsers. However, they are supported by all major browsers, including Chrome, Firefox, Safari, and Edge.

Polyfills and Workarounds: To ensure a consistent experience for users across all browsers, consider using polyfills and feature detection. Polyfills like “cqfill” can help you achieve container query-like behavior in browsers that don’t support them natively. These polyfills simulate the behavior of container queries using JavaScript and CSS.

Conclusion

In the ever-evolving landscape of web development, CSS container queries represent a significant leap forward in responsive web development. These queries offer a refreshing approach, allowing designers and developers to create layouts that are not just responsive to viewport size but also responsive to the content they contain. While browser support may still be evolving, it’s essential to embrace the potential of container queries and integrate them into your web projects. As we look toward the future, it’s clear that the ability to adapt web UIs to their content is a powerful asset. By understanding and harnessing CSS container queries, we can build web experiences that are not only visually appealing but also more user-friendly and adaptable to a wide range of devices and screen sizes. The future of responsive web development is indeed promising, and CSS container queries are at the forefront of this exciting journey. If you are not already using container queries, I encourage you to give them a try. You may be surprised at how much they can improve your web UI development.

About The Author