Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readCSS

Make a card respond to its container

Use a container size query to keep the same card stacked in a sidebar and side by side in a wide column.

You built a card with an image on the left and text on the right. It looks fine in the main column. Then you drop the same card into a 280px sidebar and the text squeezes into a thin strip next to the image.

Your breakpoint is a media query, so it checks the viewport width, regardless of space in the sidebar.

.card {
  display: flex;
  flex-direction: column;
}

@media (min-width: 700px) {
  .card {
    flex-direction: row;
  }
}

I put this card in a 900px layout with a 280px sidebar and a 604px main column, then read flex-direction at two viewport widths. At 1200px wide both cards are row, including the one in the sidebar. At 600px wide both are column, including the one with room to spare.

Ask the wrapper instead

A container size query measures an eligible ancestor. Mark the wrapper with container-type: inline-size and query its inline size.

<style>
  .slot { container-type: inline-size; }

  .card { display: flex; flex-direction: column; }

  @container (inline-size >= 480px) {
    .card { flex-direction: row; }
  }
</style>

<div class="slot">
  <article class="card">
    <img src="cover.jpg" alt="" width="96" height="96">
    <div><h3>Title</h3><p>Text</p></div>
  </article>
</div>

The card now switches to row when its .slot is at least 480px wide, wherever on the page that is.

The same measurement as before, with the sidebar and main column each wrapped in a .slot:

viewport 1200 sidebar { slotWidth: 280, flexDirection: 'column' } main { slotWidth: 604, flexDirection: 'row' }
viewport 600 sidebar { slotWidth: 280, flexDirection: 'column' } main { slotWidth: 604, flexDirection: 'row' }

The sidebar card stays stacked and the main card stays side by side, and the viewport width no longer matters.

Give the card an ancestor to query

An @container rule does not apply to the element that has container-type, only to its descendants. I set a blue background inside @container (min-width: 480px) for a 600px .slot and for a child of it. The child turned blue and the .slot stayed red.

inline-size also cuts the wrapper's width off from its contents. An inline-block with some text in it measured 184px here, and the same box with container-type: inline-size measured 0px. Put the wrapper in a slot with a width set by its layout, such as a block that fills its parent or a grid track with an assigned width.

I prefer this to a compact prop on the card. The slot decides the layout, and the card keeps working when someone moves it.