How to recreate collapsing borders on non-table elements

This post provides an example of emulating border-collapse on grid-like elements, demonstrated with a calendar.

CSS offers a handy keyword called border-collapse for tables, allowing adjacent cells to unify their borders to preserve proper cell sizes and achieve a cleaner look.

Uncollapsed Borders:

Image

Collapsed Borders:

Image

(Image Source: MDN-Docs on border-collapse))

Unfortunately, this keyword is limited to use inside <table> elements and, as of now, cannot be applied to other elements.

Since modern CSS layouts have largely moved away from tables in favor of grids or flexboxes, we lose access to this convenient feature. When laying out items in a grid, we may encounter borders of adjacent elements doubling in width, as seen in this calendar:

Image

A common workaround is to use selectors to remove borders on certain sides when an element sits next to another with a border.

Depending on selector complexity and layout choices, this is often suboptimal:

  • Missing borders may reduce cell size when using box-sizing: border-box, introducing layout issues.

  • A workaround could be setting border colors to transparent. However, this may create artifacts at border intersections. Notice the exaggerated slopes where crossing borders meet:

Image

So what can we actually do?

Abuse non-diffusing shadows to emulate border behavior.

Since we can apply multiple shadows to a single element, the possibilities are extensive. For demonstration purposes, each shadow is colored differently, accompanied by an explanation to make the code easier to follow.

  • First shadow: 2px 0 0 0 lime adds a shadow on the right.
Image
  • Second shadow: 0 2px 0 0 teal places one on the bottom.
Image
  • Third shadow: 2px 2px 0 0 red closes the corner on the bottom-right.
Image
  • Fourth shadow: 2px 0 0 0 orange inset creates a left-side shadow that overlaps with the first (lime) whenever possible. This is our first collapse-like effect, relying on how shadows are rendered in CSS.
Image
  • Fifth (and final) shadow: 0 2px 0 0 blue inset adds a top shadow that overlaps with the second (teal) where applicable.
Image

Concluding

If all shadows are colored grey, we get the following result:

box-shadow: 
  2px 0 0 0 grey,
  0 2px 0 0 grey, 
  2px 2px 0 0 grey, 
  2px 0 0 0 grey inset, 
  0 2px 0 0 grey inset;
Image

This can still be refined by:

  • shifting the entire calendar slightly left with a negative margin (since the left shadow doesn’t collapse with the outer edge),
  • adding extra left and top padding equal to the border width to nudge content toward the center of the shadow-defined boxes.
Image

And that’s it.

We’ve recreated collapsing borders without using any actual borders by repurposing some of the tools CSS gives us.