This article demonstrates how container queries in CSS create resilient, reusable components with built-in layout variations, achieving a "build once, deploy everywhere" approach. The example focuses on a subscription form adapting to different screen sizes.
The form utilizes CSS Grid for layout flexibility. Three grid areas (legend, field, submit) are defined, and their arrangement changes based on the container's width using container queries. A video shows the layout adjustments.
The .subscription-form
element is designated as the container using container-type: inline-size;
. A nested .form__content
div is targeted by the container queries:
.subscription-form { container-type: inline-size; } .form__content { display: grid; gap: 1rem; }
A first container query ( @container (min-width: 375px)
) defines the grid template for medium-sized layouts:
@container (min-width: 375px) { .form__content { grid-template-areas: "legend field" "legend submit"; align-items: center; column-gap: 2rem; } /* ... grid area assignments for legend, .form-group, button ... */ }
A second query ( @container (min-width: 700px)
) adjusts the layout for larger screens:
@container (min-width: 700px) { .form__content { grid-template-areas: "legend field submit"; } button { align-self: end; } }
Another video demonstrates the responsive behavior.
A CodePen demo provides a live, interactive example. This approach showcases the power of container queries for creating reusable and adaptable CSS components. This excerpt is from Unleashing the Power of CSS.
The above is the detailed content of Quick Tip: Shipping Resilient CSS Components. For more information, please follow other related articles on the PHP Chinese website!