DEV Community

Cover image for How to create an equal border with a display grid - Hack (HTML5 and CSS3)
Muhammad Azfar Aslam
Muhammad Azfar Aslam

Posted on • Edited on

How to create an equal border with a display grid - Hack (HTML5 and CSS3)

We have different types of displays in CSS, the most famous are as follows

  • Block
  • Flex
  • Grid
  • Table etc.

Today, I want to discuss Grid. We can fully control grid rows and columns. Grid is one of the most used CSS properties to create a Masonry gallery. Recently I was creating a table dynamically whose columns are fixed but the number of rows increases based on the number of items. Therefore, a normal table is not possible for this case scenario. Grid was the solution, I can create table alike layout and generates a dynamically exact number of columns and rows as well. The only problem left was the border. If I use border property of CSS then it will cause a double border between and one single border of the box.

I was using tailwind. A sample code and UI are something like this.

<div class="grid grid-cols-4">
   <div class="border">
      <h3 class="text-center py-6">1</h3>
   </div>
   .....
   .....
</div>
Enter fullscreen mode Exit fullscreen mode

Image description

As you guys can see the problem. I searched but no solution was available on the internet. Most of the solutions were about nth-child() but I didn't have a fixed number of items so nth-child() was not for me. I came up with a solution I wanted to share with you guys, I hope maybe it can help anyone. I used a gap and background for the border. So, this is how my code and UI look after this idea.

<div
  class="grid grid-cols-4 bg-black border border-black"
  style="gap: 1px">
    <div class="bg-white">
       <h3 class="text-center py-6">1</h3>
    </div>
    ....
    ....
</div>
Enter fullscreen mode Exit fullscreen mode

Image description

Thank you for your time.


Other links:

Top comments (0)