Shipping Resilient CSS Components — SitePoint

In this quick tip excerpted from Unleashing the Power of CSS, Stephanie shows how container queries enable us to ship resilient components containing built-in layout and style variants.

It might seem quite bold to say, but container queries allow us to apply the “build once, deploy everywhere” methodology. As a design systems engineer, it really appeals to me to be able to ship design system components with built-in layout and style variants.

To demonstrate this idea, the image below shows a subscription form. Container queries have been applied, and the component is shown in a full-width area within the narrower space of the sidebar and at the medium width within the content area.

Grid is an excellent companion for composing these variants. Using grid template areas, we’re able to rearrange the form sections without the need for extra markup. In this subscription form component, I’ve identified three grid areas: legend, field, and submit. The overlays added in the following video show how the layout changes across the variants.

In the code for the subscription form, the <form> element has a class subscription-form and is set as the container. A nested <div> with a class of form-content is what our container queries will then modify:

.subscription-form {
  container-type: inline-size;
}

At the narrowest default width, the form is a simple grid stack with a gap applied:

.form__content {
  display: grid;
  gap: 1rem;
}

The first container query for the mid-sized layout is doing the heavy lifting of creating the grid template and assigning all of the elements to the grid areas:

@container (min-width: 375px) {
  .form__content {
    grid-template-areas: 
            "legend field" 
            "legend submit";
    align-items: center;
    column-gap: 2rem;
  }

  legend {
    grid-area: legend;
  }

  .form-group {
    grid-area: field;
  }

  button {
    grid-area: submit;
  }
}

The second, final container query then only has to adjust the grid-template-areas definition to horizontally line up the areas. Only one additional tweak is needed, which is to realign the Subscribe button to the end position, which visually aligns it to the email input:

@container (min-width: 700px) {
  .form__content {
    grid-template-areas: 
            "legend field submit";
  }

  button {
    align-self: end;
  }
}

The following video clip shows the subscription form layout adjusting as the width is reduced.

The following CodePen demo provides a live example of this form form layout (with “Resize me!” handles).

See the Pen
Container Queries for Subscription Form
by SitePoint (@SitePoint)
on CodePen.

As you can see, container queries offer us the capability to build components that can be reused anywhere.

This article is excerpted from Unleashing the Power of CSS: Advanced Techniques for Responsive User Interfaces, available on SitePoint Premium.




Source link