Collapse Border in CSS Grid

Sep 20, 2024

What is border-collapse

border-collapse is a CSS property that merges adjacent table borders into a single border.

For example, if you have a 1px border around two adjacent cells, the overlapping border will be 2px. With border-collapse enabled, the borders merge, and the overlap will only be 1px.

Unfortunately, border-collapse can only be use with tables.

Notice how the inner borders are thicker than the outer ones in the example below.

Code Playground
export default function Example() {
  return (
    <div className="p-4 w-full h-screen ">
      <div className="grid grid-cols-2">
        {[...Array(4)].map((element, index) => (
          <div className="border border-red-400 p-5 text-white" key={index}>
            {index}
          </div>
        ))}
      </div>
    </div>
  )
}

Here a simple workaround to replicate this behavior in CSS grid in three easy steps.

Apply a border on all sides to each grid item.

Code Playground
export default function Example() {
  return (
    <div className="p-4 w-full h-screen  text-white">
      <div className="grid grid-cols-2">
        {[...Array(4)].map((element, index) => (
          <div className="border border-gray-400 p-5" key={index}>
            {index}
          </div>
        ))}
      </div>
    </div>
  )
}

Apply margin-top: -1px and margin-left: -1px to each grid item.

This will stack the borders on top of each other similar to border-collapse and causes an offset relative to the grid parent.

💡

I added a border to the grid parent to highlight this offset and why the next step is necessary.

Code Playground
export default function Example() {
  return (
    <div className="p-4 w-full h-screen  text-white">
      <div className="grid grid-cols-2 border border-red-400">
        {[...Array(4)].map((element, index) => (
          <div className="-ml-px -mt-px border border-gray-400 p-5" key={index}>
            {index}
          </div>
        ))}
      </div>
    </div>
  )
}

Apply padding-top: 1px and padding-left: 1px to the grid parent.

This will offset the margin-top: -1px and margin-left: -1px.

Code Playground
export default function Example() {
  return (
    <div className="p-4 w-full h-screen  text-white">
      <div className="pt-px pl-px grid grid-cols-2 border border-red-400">
        {[...Array(4)].map((element, index) => (
          <div className="-ml-px -mt-px border border-gray-400 p-5" key={index}>
            {index}
          </div>
        ))}
      </div>
    </div>
  )
}