HomeServiceContact
Drupal
min read
February 16, 2024

Container Queries: Harnessing Responsive Design at the Component Level

Container Queries: Harnessing Responsive Design at the Component Level
Table of contents

Responsive web design has evolved over the years to adapt to a wide range of devices and screen sizes. A new addition to the toolkit is the concept of **Container Queries**, a powerful feature that allows components to adapt their styling based on the dimensions of their containing element.

 What is `container-type`?

In the world of container queries, the `container-type` is a pivotal attribute. It defines the nature of the container being queried and determines how the contained elements should react to changes in the container's dimensions.

Different Values of `container-type`

1. inline (Default):

   - This is the default value when `container-type` is not explicitly set.

   - Ideal for inline elements or components that naturally flow with surrounding content.

   

@container (min-width: 600px, container-type: inline) {
    /* Your styles for larger inline containers go here */
  }

2. block (Block-level Container):

   - Used for block-level containers like divs or sections.

   - Especially useful when styling components that are expected to take up the full width of their parent.

   

@container (min-width: 600px, container-type: block) {
    /* Your styles for larger block-level containers go here */
  }

3. grid (Grid Container):

   - Suitable for containers that follow a grid layout, such as a multi-column grid.

   - Enables fine-tuning styles for different grid structures.

@container (min-width: 600px, container-type: grid) {
    /* Your styles for larger grid-based containers go here */}

4. Stack (Stacking Context):

   - This type is used when components are arranged in a stacking context.

   - Useful for scenarios where elements are layered on top of each other.

 

  @container (min-width: 765px, container-type: stack) {
    /* Your styles for larger stacking context containers go here */
  }

Media query vs container query

Container queries are a powerful addition to the capabilities of CSS, particularly in the realm of responsive web design. They allow components to respond to the size of their containing element rather than the viewport, offering a more granular and dynamic approach to styling.

However, while container queries bring significant benefits, they are not meant to replace media queries but rather complement them. Both have distinct use cases and functionalities.

Media Queries:

- Media queries are designed to respond to the characteristics of the viewport, such as screen width, height, or device orientation.

- They are essential for adapting the overall layout and styles of a page based on the device or screen size.

- Media queries are well-established and widely supported, making them a fundamental tool for responsive design.

Container Queries:

- Container queries focus on adjusting the styles of individual components based on the dimensions of their containing element.

- They provide a more modular and component-centric approach, allowing for targeted adjustments within a larger layout.

- Container queries are particularly useful for components with varying sizes and positions within a flexible layout.

Coexistence

- Media queries and container queries can work together seamlessly. Media queries set the overall layout, and container queries fine-tune individual components within that layout.

- Media queries are still crucial for addressing global layout changes, such as switching between a desktop and mobile layout.

- Container queries shine when it comes to making components adapt gracefully within their containers.

In summary, container queries enhance the developer's toolkit for responsive design, offering more control at the component level. While they provide a powerful way to address certain challenges, media queries remain essential for handling broader layout adjustments based on the viewport. The combination of both allows for a comprehensive and flexible approach to responsive web design. 

Container Queries in Action: Card Example

Let's illustrate the power of container queries with a practical example involving a responsive card layout.

We want different designs for card when the width is less then 766px 

Vertical layout

Horizontal layout

Consider a content group with a dynamic column layout ranging from 1 to 4 columns. Within this layout, cards can be added, each specifying its width (`span1`, `span2`, `span3`, `span4`). Depending on the container width, the card layout adjusts for optimal user experience.

Below is the example of different layouts for columns and 4 column span functionality 

Below is the html file


<html>
 <head>
   <link rel="stylesheet" href="styles.css">
   <script>
     function addCard() {
       var cardWidth = document.getElementById("card-width").value;
       var layout = document.getElementById("layout").value;
    
       var card = document.createElement("div");
       card.className = "content_group_item " + cardWidth;
       card.innerHTML += '<div class="wrapper"><div class="box">Box</div><div class="description">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div></div>';
    
       var container = document.getElementById("contentGroup");
       container.className = "content_group " + layout;
       container.appendChild(card);
     }
   </script>
 </head>
 <body>
   <!-- Example: Card within a 2-column layout (col-2) -->
   <h1>Content Group - Grid</h1>
   <form>
     <label for="layout">Select Layout:</label>
     <select id="layout">
       <option value="one_col">Column 1 (12 grid each)</option>
       <option value="two_col">Column 2 (6 grid each)</option>
       <option value="three_col">Column 3 (4 grid each)</option>
       <option value="four_col">Column 4 (3 grid each)</option>
       <option value="six_col">Column 6 (2 grid each)</option>
     </select>
     <br />
     <label for="card-width">Select Card Width:</label>
     <select id="card-width">
       <option value="span_one">Span 1</option>
       <option value="span_two">Span 2</option>
       <option value="span_three">Span 3</option>
       <option value="span_four">Span 4</option>
     </select>
  
     <button type="button" onclick="addCard()">Add Card</button>
   </form>
  
  
  
   <div class="container">
     <h2 class="title">Faculty</h2>
     <p class="text">Change lives, change organizations, change the world.</p>
     <div class="content_group" id="contentGroup"> 
     </div>
   </div>
 </body>
</html>


Below is the css file


form {
 border: 2px dashed #ccc;
 padding: 1rem;
}


.content_group {
 display: flex;
 justify-content: space-between;
 margin-bottom: 20px;
}


.content_group_item {
 border: 1px solid #ccc;
 padding: 10px;
 margin-bottom: 10px;
}




h2 {
 margin: 0;
 font-size: 30px;
 font-style: normal;
 font-weight: 700;
 line-height: 1.6;
}
p {
 font-size: 26px;
 font-style: normal;
 font-weight: 400;
 line-height: 1.5;
}
.container {
 width: 1190px;
 margin: 1rem auto;
 padding: 1rem;
 border: 2px dashed #ccc;
}
.one_col{
 display: grid;
 grid-template-columns: repeat(1, 1fr);
 grid-auto-flow: dense;
 gap: 0;
}
.two_col{
 display: grid;
 grid-template-columns: repeat(2, 1fr);
 grid-auto-flow: dense;
 gap: 40px;
}
.three_col{
 display: grid;
 grid-template-columns: repeat(3, 1fr);
 grid-auto-flow: dense;
 gap: 40px;
}
.four_col{
 display: grid;
 grid-template-columns: repeat(4, 1fr);
 grid-auto-flow: dense;
 gap: 40px;
}
.six_col{
 display: grid;
 grid-template-columns: repeat(6, 1fr);
 grid-auto-flow: dense;
 gap: 30px;
}
.content_group_item {
 margin: 0;
 grid-template-rows: 1fr auto;
}


.span_two {
 grid-column-end: span 2;
}
.span_three {
 grid-column-end: span 3;
}
.span_four {
 grid-column-end: span 4;
}
.span_five {
 grid-column-end: span 5;
}


.box {
 border: 1px solid #222;
 color: #222;
 background-color:#ddd;
 display: flex;
 font-size: 30px;
 justify-content: center;
 align-items: center;
 min-height: 250px;
 margin-bottom: 20px;
}


.content_group_item {
 container-type: inline-size;
}


@container (min-width: 766px) {
 .wrapper {
   display: flex;
 }


 .box {
   min-width: 200px;
   margin-right: 20px;
   margin-bottom: 0;
 }
}

In these examples, we have cards within 2, 3, and 4-column layouts (`col-2`, `col-3`, `col-4`). Each card specifies its span (`span1`, `span2`, `span3`, `span4`). The width of the cards adapts dynamically based on the specified span value, ensuring a responsive and visually appealing layout for different column structures.

Conclusion

In the ever-evolving landscape of web development, Container Queries emerge as a game-changer in responsive design. This feature empowers developers to tailor component styles dynamically based on the dimensions of their containing elements, providing a level of adaptability beyond traditional media queries.

Responsive Adaptability

Container Queries offer unparalleled adaptability, allowing components to respond dynamically to changes in container dimensions. This ensures a seamless user experience across various devices and screen sizes.

Versatility of container-type

The introduction of the `container-type` attribute enhances the flexibility of Container Queries. Whether dealing with inline elements, block-level containers, grid layouts, or stacking contexts, developers can precisely tailor styles to the nature of the container.

Practical Implementation: Card Layout:

The practical example of a responsive card layout showcases the versatility of Container Queries. The ability to seamlessly adjust the layout of cards within a dynamic column structure ensures a cohesive and optimized user experience.

Best Practices for Integration:

Effective utilization of Container Queries requires adherence to best practices. Embrace progressive enhancement, conduct thorough testing, and maintain a well-organized codebase for a smooth and maintainable implementation.

Looking Ahead: Future of Responsive Design:

As Container Queries continue to gain support, they signify a significant step forward in the evolution of responsive design. The feature promises a future where web layouts are more adaptable, context-aware, and user-centric.

Embrace the Responsive Revolution:

In conclusion, Container Queries empower developers to create designs that seamlessly adapt to diverse contexts and devices. As browser support grows, integrating Container Queries into your toolkit becomes an exciting prospect for staying at the forefront of responsive web development. Embark on the journey of the responsive revolution, experiment with Container Queries, and elevate the user experience on the web.

Written by
Artwork by
No art workers.
We'd love to talk about your business objectives