htmlcssflexboxtailwind-css

How do I get a flex wrap element to shrink when it starts wrapping


I have a row flex-wrap element with a gray background.

enter image description here

enter image description here

How can I get it to shrink so it doesn't show take up this empty space.

Current code

<div class="flex flex-col h-100 items-center justify-center bg-black">
  <div class="inline-flex shrink flex-wrap justify-center gap-2 bg-gray-600">
    <div class="h-20 w-52 bg-white"></div>
    <div class="h-20 w-52 bg-white"></div>
    <div class="h-20 w-52 bg-white"></div>
  </div>
</div>

Code in Playground: https://play.tailwindcss.com/16OSgVOqBc


Solution

  • There isn't any "automatic" way to do this with CSS, but you can set up container query breakpoints to shrink the parent element to the widths where the elements would wrap:

    <script src="https://unpkg.com/@tailwindcss/browser@4.1.3"></script>
    
    <div class="flex flex-col h-100 items-center justify-center bg-black @container">
      <div class="
        inline-flex shrink flex-wrap justify-center gap-2 bg-gray-600
        max-w-[13rem] @min-[26.5rem]:max-w-[calc(var(--spacing)*106)] @min-[40.5rem]:max-w-none
      ">
        <div class="h-20 w-52 bg-white"></div>
        <div class="h-20 w-52 bg-white"></div>
        <div class="h-20 w-52 bg-white"></div>
      </div>
    </div>

    You can also use CSS variables to better express where the numbers come from:

    <script src="https://unpkg.com/@tailwindcss/browser@4.1.3"></script>
    
    <div class="flex flex-col h-100 items-center justify-center bg-black @container">
      <div class="
        inline-flex shrink flex-wrap justify-center gap-2 bg-gray-600
        max-w-(--width) @min-[26.5rem]:max-w-[calc((var(--width)*2)+var(--gap))] @min-[40.5rem]:max-w-none
        [--width:calc(var(--spacing)*52)]
        [--gap:calc(var(--spacing)*2)]"
      >
        <div class="h-20 w-(--width) bg-white"></div>
        <div class="h-20 w-(--width) bg-white"></div>
        <div class="h-20 w-(--width) bg-white"></div>
      </div>
    </div>

    Though unfortunately, CSS variables can't be used in container queries.