Featured image of post Practical use of modern CSS new features (subgrid/container queries)Featured image of post Practical use of modern CSS new features (subgrid/container queries)

Practical use of modern CSS new features (subgrid/container queries)

Paradigm shift from Viewport standards to free-standing components

Traditional responsive web design relies on the overall width of the screen (viewport). However, in today’s world of component-oriented design, the available width of UI parts differs depending on the parent element (sidebar or main column) in which they are placed.

With the advent of CSS Grid’s “Subgrid” and “Container Queries”, layout flexibility and maintainability have dramatically improved.


Recipe 1: subgrid to synchronize button positions while aligning card heights

Even if the number of characters in the title is uneven in a multi-column card UI, the heights of “images, titles, text, and buttons” in each card can be perfectly aligned in a horizontal line.

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 1.5rem;
}

.card {
  display: grid;
  grid-template-rows: subgrid;
  grid-row: span 4; /* 画像・タイトル・本文・フッターの4行を親グリッドに同期 */
}

There is no need for any JavaScript to calculate the height for each card.

Recipe 2: @container whose layout adapts according to its width

The card component automatically switches between horizontal and vertical alignment depending on the width of the container in which it is placed.

.card-wrapper {
  container-type: inline-size;
  container-name: card-container;
}

@container card-container (min-width: 450px) {
  .card-content {
    flex-direction: row; /* 横幅に余裕があれば横並びへ自動変形 */
  }
}

You can reuse the same components for both the wide area of the home page and the narrow area of the sidebar.


Concept of practical implementation

Subgrids and container queries have already reached full support in major modern browsers. Get rid of the ruin caused by breakpoints across the entire screen and move to a CSS design where each component can stand on its own.