Web-Design
Monday May 24, 2021 By David Quintanilla
Use-Cases And Migration Strategies — Smashing Magazine


About The Creator

Adrian Bece is a flexible fullstack internet developer with intensive eCommerce expertise who’s presently working at PROTOTYP as a technical lead. He enjoys …
More about
Adrian

Container queries have been just lately added to Chrome Canary and the developer neighborhood is worked up in regards to the potential styling enhancements. This game-changing characteristic brings media queries nearer to the goal parts themselves and allows them to adapt to nearly any given container or format, leading to extra sturdy, reusable, and maintainable part types. On this article, we’re going to cowl container question fundamentals and the way to use them as we speak with progressive enhancement or polyfills.

After we write media queries for a UI component, we all the time describe how that component is styled relying on the display dimensions. This method works nicely when the responsiveness of the goal component media question ought to solely rely on viewport dimension. Let’s check out the next responsive web page format instance.

Responsive page layout example. The left image shows the desktop layout at 1280px viewport width and the right image shows the mobile layout at 568px viewport width.
Responsive web page format instance. The left picture reveals the desktop format at 1280px viewport width and the suitable picture reveals the cellular format at 568px viewport width. (Large preview)

Nonetheless, responsive Internet Design (RWD) isn’t restricted to a web page format — the person UI elements normally have media queries that may change their model relying on the viewport dimensions.

Responsive product card component example. The left image shows a component at 720px viewport width and the right image shows component layout at 568px viewport width.
Responsive product card part instance. The left picture reveals a part at 720px viewport width and the suitable picture reveals part format at 568px viewport width. (Large preview)

You might need already seen an issue with the earlier assertion — particular person UI part format usually doesn’t rely completely on the viewport dimensions. Whereas web page format is a component carefully tied to viewport dimensions and is among the topmost parts in HTML, UI elements can be utilized in numerous contexts and containers. If you consider it, the viewport is only a container, and UI elements may be nested inside different containers with types that have an effect on the part’s dimensions and format.

Example of page layout with the same product card UI component in the top section 3-column grid and the bottom section list.
Instance of web page format with the identical product card UI part within the high part 3-column grid and the underside part listing. (Large preview)

Regardless that the identical product card part is utilized in each the highest and backside sections, part types not solely rely on the viewport dimensions but in addition rely on the context and the container CSS properties (just like the grid within the instance) the place it’s positioned.

After all, we will construction our CSS so we assist the model variations for various contexts and containers to handle the format situation manually. Within the worst-case situation, this variation can be added with model override which might result in code duplication and specificity points.

.product-card {
    /* Default card model */
}

.product-card--narrow {
   /* Type variation for slim viewport and containers */
}

@media display and (min-width: 569px) {
 .product-card--wide {
     /* Type variation for wider viewport and containers */
  }
}

Nonetheless, that is extra of a workaround for the constraints of media queries reasonably than a correct answer. When writing media queries for UI parts we’re looking for a “magic” viewport worth for a breakpoint when the goal component has minimal dimensions the place the format doesn’t break. Briefly, we’re linking a “magical” viewport dimension worth to component dimensions worth. This worth is normally completely different from than viewport dimension and is susceptible to bugs when inside container dimensions or format adjustments.

Example of how media query cannot be reliably linked to element dimensions. Various CSS properties can affect element dimensions within a container. In this example, container padding is different between the two images.
Instance of how media question can’t be reliably linked to component dimensions. Varied CSS properties can have an effect on component dimensions inside a container. On this instance, container padding is completely different between the 2 photos. (Large preview)

The next instance showcases this precise situation — despite the fact that a responsive product card component has been carried out and it appears to be like good in a regular use-case, it appears to be like damaged if it’s moved to a special container with CSS properties that have an effect on component dimensions. Every further use-case requires further CSS code to be added which might result in duplicated code, code bloat, and code that’s tough to keep up.

See the Pen [Product cards – various containers](https://codepen.io/smashingmag/pen/abJpgvj) by Adrian Bece.

See the Pen Product cards – various containers by Adrian Bece.

This is among the points that container queries making an attempt to repair. Container queries lengthen present media queries performance with queries that rely on the goal component dimensions. There are three main advantages of utilizing this method:

  • Container question types are utilized relying on the scale of the goal component itself. UI elements will have the ability to adapt to any given context or container.
  • Builders gained’t must search for a “magic quantity” viewport dimension worth that hyperlinks a viewport media question to a goal dimension of UI part in a particular container or a particular context.
  • No want so as to add further CSS lessons or media queries for various contexts and use-cases.

“The perfect responsive web site is a system of versatile, modular elements that may be repurposed to serve in a number of contexts.”

— “Container Queries: Once More Unto the Breach,” Mat Marquis

Earlier than we dive deep into container queries, we have to take a look at the browser assist and see how we will allow the experimental characteristic in our browser.

Browser Assist

Container queries are an experimental feature, obtainable presently in Chrome Canary model on the time of writing this text. If you wish to observe alongside and run the CodePen examples on this article you’ll must allow container queries within the following settings URL.

chrome://flags/#enable-container-queries
Container queries
(Large preview)

In case you’re utilizing a browser that doesn’t assist container queries, a picture showcasing the meant working instance can be supplied alongside the CodePen demo.

Working With Container Queries

Container queries are usually not as simple as common media queries. We’ll have so as to add an additional line of CSS code to our UI component to make container queries work, however there’s a purpose for that and we’ll cowl that subsequent.

Containment Property

CSS comprise property has been added to nearly all of trendy browsers and has a good 75% browser support on the time of writing this text. The comprise property is especially used for efficiency optimization by hinting to the browser which components (subtrees) of the web page may be handled as unbiased and gained’t have an effect on the adjustments to different parts in a tree. That method, if a change happens in a single component, the browser will re-render solely that half (subtree) as an alternative of the entire web page. With comprise property values, we will specify which forms of containment we need to use — format, dimension, or paint.

There are a lot of great articles in regards to the comprise property that define obtainable choices and use-cases in far more element, so I’m going to focus solely on properties associated to container queries.

What does the CSS contentment property that’s used for optimization need to do with container queries? For container queries to work, the browser must know if a change happens within the component’s kids format that it ought to re-render solely that part. The browser will know to use the code within the container question to the matching part when the part is rendered or the part’s dimension adjustments.

We’ll use the format worth for the comprise property, however we’ll additionally want an additional value that alerts the browser in regards to the axis wherein the change will happen.

  • inline-size
    Containment on the inline axis. It’s anticipated for this worth to have considerably extra use-cases, so it’s being carried out first.
  • block-size
    Containment on block axis. It’s nonetheless in growth and isn’t presently obtainable.

One minor draw back of the comprise property is that our format component must be a baby of a comprise component, which means that we’re including an extra nesting degree.

<part>
  <article class="card">
      <div class="card__wrapper">
          <!-- Card content material -->       
      </div>
  </article>
</part>
.card {
   comprise: format inline-size;
}

.card__wrapper {
  show: grid;
  grid-gap: 1.5em;
  grid-template-rows: auto auto;
  /* ... */
}

Discover how we aren’t including this worth to a extra distant parent-like part and maintaining the container as near the affected component as attainable.

“Efficiency is the artwork of avoiding work and making any work you do as environment friendly as attainable. In lots of circumstances, it’s about working with the browser, not in opposition to it.”

— “Rendering Performance,” Paul Lewis

That’s the reason we should always accurately sign the browser in regards to the change. Wrapping a distant father or mother component with a comprise property may be counter-productive and negatively have an effect on web page efficiency. In worst-case eventualities of misusing the comprise property, the format could even break and the browser gained’t render it accurately.

Container Question

After the comprise property has been added to the cardboard component wrapper, we will write a container question. We’ve added a comprise property to a component with card class, so now we will embrace any of its baby parts in a container question.

Similar to with common media queries, we have to outline a question utilizing min-width or max-width properties and nest all selectors contained in the block. Nonetheless, we’ll be utilizing the @container key phrase as an alternative of @media to outline a container question.

@container (min-width: 568px) {
  .card__wrapper {
    align-items: heart;
    grid-gap: 1.5em;
    grid-template-rows: auto;
    grid-template-columns: 150px auto;
  }

  .card__image {
    min-width: auto;
    peak: auto;
  }
}

Each card__wrapper and card__image component are kids of card component which has the comprise property outlined. After we substitute the common media queries with container queries, take away the extra CSS lessons for slim containers, and run the CodePen instance in a browser that helps container queries, we get the next consequence.

In this example, we’re not resizing the viewport, but the <section> container element itself that has resize CSS property applied. The component automatically switches between layouts depending on the container dimensions.
On this instance, we’re not resizing the viewport, however the <part> container component itself that has resize CSS property utilized. The part mechanically switches between layouts relying on the container dimensions. (Large preview)

See the Pen [Product cards – container queries](https://codepen.io/smashingmag/pen/VwpPJmO) by Adrian Bece.

See the Pen Product cards – container queries by Adrian Bece.

Please word that container queries presently don’t present up in Chrome developer instruments, which makes debugging container queries a bit tough. It’s anticipated that the correct debugging assist can be added to the browser sooner or later.

You may see how container queries permit us to create extra sturdy and reusable UI elements that may adapt to nearly any container and format. Nonetheless, correct browser assist for container queries continues to be far-off within the characteristic. Let’s attempt to see if we will implement container queries utilizing progressive enhancement.

Progressive Enhancement & Polyfills

Let’s see if we will add a fallback to CSS class variation and media queries. We will use CSS feature queries with the @helps rule to detect obtainable browser options. Nonetheless, we cannot check for other queries, so we have to add a verify for a comprise: format inline-size worth. We’ll need to assume that browsers that do assist inline-size property additionally assist container queries.

/* Test if the inline-size worth is supported */
@helps (comprise: inline-size) {
  .card {
    comprise: format inline-size;
  }
}

/* If the inline-size worth isn't supported, use media question fallback */
@helps not (comprise: inline-size) {
    @media (min-width: 568px) {
       /* ... */
  }
}

/* Browser ignores @container if it’s not supported */
@container (min-width: 568px) {
  /* Container question types */
}

Nonetheless, this method may result in duplicated types as the identical types are being utilized each by container question and the media question. Should you resolve to implement container queries with progressive enhancement, you’d need to use a CSS pre-processor like SASS or a post-processor like PostCSS to keep away from duplicating blocks of code and use CSS mixins or one other method as an alternative.

See the Pen [Product cards – container queries with progressive enhancement](https://codepen.io/smashingmag/pen/MWpJMpr) by Adrian Bece.

See the Pen Product cards – container queries with progressive enhancement by Adrian Bece.

Since this container question spec continues to be in an experimental section, it’s necessary to understand that the spec or implementation is inclined to vary in future releases.

Alternatively, you should use polyfills to offer a dependable fallback. There are two JavaScript polyfills I’d like to spotlight, which presently appear to be actively maintained and supply vital container question options:

Migrating From Media Queries To Container Queries

Should you resolve to implement container queries on an present venture that makes use of media queries, you’ll must refactor HTML and CSS code. I’ve discovered this to be the quickest and most simple method of including container queries whereas offering a dependable fallback to media queries. Let’s check out the earlier card instance.

<part>
      <div class="card__wrapper card__wrapper--wide">
          <!-- Vast card content material -->       
      </div>
</part>

/* ... */

<apart>
      <div class="card__wrapper">
          <!-- Slender card content material -->        
      </div>
</apart>
.card__wrapper {
  show: grid;
  grid-gap: 1.5em;
  grid-template-rows: auto auto;
  /* ... */
}

.card__image {
  /* ... */
}

@media display and (min-width: 568px) {
  .card__wrapper--wide {
    align-items: heart;
    grid-gap: 1.5em;
    grid-template-rows: auto;
    grid-template-columns: 150px auto;
  }

  .card__image {
    /* ... */
  }
}

First, wrap the basis HTML component that has a media question utilized to it with a component that has the comprise property.

<part>
  <article class="card">
      <div class="card__wrapper">
          <!-- Card content material -->        
      </div>
  </article>
</part>
@helps (comprise: inline-size) {
  .card {
    comprise: format inline-size;
  }
}

Subsequent, wrap a media question in a characteristic question and add a container question.

@helps not (comprise: inline-size) {
    @media (min-width: 568px) {
    .card__wrapper--wide {
       /* ... */
    }

    .card__image {
       /* ... */
    }
  }
}


@container (min-width: 568px) {
  .card__wrapper {
     /* Similar code as .card__wrapper--wide in media question */
  }

  .card__image {
    /* Similar code as .card__image in media question */
  }
}

Though this technique ends in some code bloat and duplicated code, by utilizing SASS or PostCSS you’ll be able to keep away from duplicating growth code, so the CSS supply code stays maintainable.

As soon as container queries obtain correct browser assist, you may need to think about eradicating @helps not (comprise: inline-size) code blocks and proceed supporting container queries completely.

Stephanie Eckles has just lately printed an amazing article on container queries protecting numerous migration strategies. I like to recommend checking it out for extra info on the subject.

Use-Case Situations

As we’ve seen from the earlier examples, container queries are greatest used for extremely reusable elements with a format that depends upon the obtainable container area and that can be utilized in numerous contexts and added to completely different containers on the web page.

Different examples embrace (examples require a browser that helps container queries):

Conclusion

As soon as the spec has been carried out and broadly supported in browsers, container queries may change into a game-changing characteristic. It’ll permit builders to jot down queries on part degree, transferring the queries nearer to the associated elements, as an alternative of utilizing the distant and barely-related viewport media queries. It will lead to extra sturdy, reusable, and maintainable elements that may have the ability to adapt to numerous use-cases, layouts, and containers.

Because it stands, container queries are nonetheless in an early, experimental section and the implementation is inclined to vary. If you wish to begin utilizing container queries in your tasks as we speak, you’ll want so as to add them utilizing progressive enhancement with characteristic detection or use a JavaScript polyfill. Each circumstances will lead to some overhead within the code, so in case you resolve to make use of container queries on this early section, be certain to plan for refactoring the code as soon as the characteristic turns into broadly supported.

References

Smashing Editorial
(vf, yk, il)



Source link