Smart borders between flex items – the dumb way

Caution, stupid code ahead.

When creating a component that adapts to available space without using Media Queries, I found myself in a situation where I had two items and wanted a border between them, regardless if they were side by side or on top of one another. The border would be left (or right) when items lined up horizontally, but top (or bottom) when the items lined up vertically.

In essence, I wanted border-between or somesuch property to exist.

With a little fiddling and some brain ping-pong with Robin, I came up with the following solution:

CodePen example

.container {
  display: flex;
  flex-wrap: wrap;
  overflow: hidden;

.item {
  flex: 1 1 20em;
  background-color: hotpink;
  border-top: 1px solid purple;
  border-left: 1px solid purple;
  margin-top: -1px;
  margin-left: -1px;

...where the border is always present on top/left, but hidden with negative margins. Ouch. Caveats: lots, probably. Not least that this only works (nicely) in a pretty limited set of circumstances.

Then, I thought, ”wait, I could just use the logical direction keywords (border-block-start vs border-inline-start etc) in modern browsers”, quickly followed by, ”no, I can’t – the logical direction isn’t actually changing.” Oh well.

Current status: feeling clever/feeling dirty.