CSS Tricks
Borders
Dynamic Grid
Dynamic Internal Grid Border CSS Trick
While building this site I ran into an interesting issue. I wanted to create a dynamic grid of cards that would only have internal borders

Above is an example of what I’m referring to. You can see that the leftmost card doesn’t have a left border, and the rightmost card doesn’t have a right border.
My initial thought was to only add borders to the 2nd and 3rd items. This would technically work if you knew for sure you would always have 4 items. For this blog site, I needed something more flexible. I wanted a solution that could handle any number of items while only displaying borders on the inside. I tried several different approaches using modulo operations and counting elements, but they were all too rigid for my use case. After searching the internet for hours, I finally found an elegant solution that’s both flexible and easy to implement—without relying on counting specific divs.
Implementation
Here’s a brief overview of how this works. Instead of counting the cards, we give each card a pseudo-element! I’ll show you the CodePen first, then dive into it a bit more if you’re interested.
What we do is create a container for our cards and give it a class, grid-block. Its display is set to grid, and the grid gap is set to 2rem (this number is important for something we’ll do later). It’s also important that we set the overflow to hidden.
Next, we create our cards and give them a position of relative. We need the relative position because we want to absolutely position our pseudo-element within each card. Other than setting the position to relative, you can style the cards however you want.
Now, here’s where the magic happens! The pseudo-elements are what make this work and stay flexible. You can set the background color of the pseudo-element to whatever color you want your border to be. The width of this element will be the width of your border. To make this work, we set the right position to half of our grid gap but negative. This is key because it moves the border between the cards, and for the last element, it moves the border out of the bounds of the grid block (with overflow hidden). This prevents the rightmost card from showing a border.
Feel free to play around with the CodePen! Try adjusting the columns variable to see how it can work for any given amount of items. You can also add a top border using similar logic: create another pseudo-element, set the width to 100% and the height to the border width, and position it at the top using top: -1px.