Tibor Udvari

Flexbox Wrap Border Collapse Effect

20 Feb 2025, 00:43 CET

I had to create a layout similar to what the border-collapse property does for tables in Tailwind but for elements in a flex-wrap. My first instinct was to try borders with some negative margin wizardry, but that didn’t work since there is no way of knowing which elements wrapped without Javascript.

Conceptually, I needed a line centered on the edge of a container, with half of its width on the inside and the other half extending outwards to overlap with the neighboring containers—a fancy way of saying a centered border if there were one.

As a Tailwind user, I tried the ring utility, but I could not find a way to have an outside and an inset ring simultaneously. Luckily, this is only a Tailwind limitation: there can be an arbitrary number of box-shadows on an element.

There’s even a handy box-shadow editor over at MDN.

Given this knowledge, the solution was a piece of cake: combine an inset and outset box-shadow to have everything stack up nicely, and add extra spacing inside the parent container to compensate for the outset width.

<div class="flex flex-wrap m-[1px]">
  <div class="[box-shadow:0_0_0_1px_black,inset_0_0_0_1px_black]">Box 1</div>
  <div class="[box-shadow:0_0_0_1px_black,inset_0_0_0_1px_black]">Box 2</div>
  <div class="[box-shadow:0_0_0_1px_black,inset_0_0_0_1px_black]">Box 3</div>
</div>

References