Explain Codes LogoExplain Codes Logo

Space between divs - display table-cell

html
responsive-design
css
layout
Alex KataevbyAlex Kataev·Jan 4, 2025
TLDR

The solution to your problem might be the border-spacing property, which you can use on a display: table; container:

<div style="display: table; border-spacing: 10px;"> <div style="display: table-cell; background-color: red;">Cell 1</div> <div style="display: table-cell; background-color: green;">Cell 2</div> </div>

Change the value 10px to your desired gap width. The border-spacing property determines the gap between the cells. Be careful when using border-collapse in conjunction with border-spacing, the former can override the latter.

Advancing your understanding: Alternative spacing methods

Playing inside the box with padding and background-clip

Padding inside table-cell elements won't cause a gap between cells. However, combined with background-clip: padding-box;, you can simulate a space:

.table-cell { display: table-cell; padding: 10px; background-clip: padding-box; }

This clips any borders or backgrounds to the padding box, keeping them from entering the spaces.

Insiders' secret: Creating spacers with table-cell

Add an extra div with display: table-cell; between your content divs. This will act as a fixed-width spacer:

<div style="display: table;"> <div style="display: table-cell;">Cell 1</div> <div style="display: table-cell; width: 20px;"></div> <!-- I'm just a spacer living in between cells 👽 --> <div style="display: table-cell;">Cell 2</div> </div>

Future-proof your code: flexbox

Flexbox is a modern layout model designed to tackle issues like the one you're facing. Set display: flex; to your container and set justify-content: space-between; to spread the children evenly:

.flex-container { display: flex; justify-content: space-between; /* Alien language for "Hey kids, make space!" 👾 */ }

This is an efficient way to embrace the fluidity of modern web layouts.

Mastering the old ways: IE8 compatibility

For IE8 compatibility, swap transparent borders with white borders (or the color of the table's background) as it does not support background-clip:

.table-cell { display: table-cell; border: 5px solid white; /* Old school cool 😎 */ }

The Small print: Understanding the limitations

Here're some caveats to be aware of when using display: table-cell;:

  • Margins don't work between table cells.
  • Float might disrupt table cells.
  • Watch out for how cell backgrounds and borders affect spacing.