There are multiple tables on a single page that need to be separated by some space. However, some of the tables have empty cells, resulting in zero height, and I do not want any extra spacing between them.
Although margin collapsing is typically an effective method for adding space, tables establish a block formatting context (BCF), which prevents margin collapsing between boxes that establish a BCF.
An example can be seen with the snippet below: there is 1em space between "1" and "2", but 2em space between "2" and "3. Ideally, I would always like to maintain a consistent 1em space. How can this be achieved?
Note: There are certain limitations to consider - it is not possible to remove markup from the empty tables or add specific classes to them. However, a container could be added for each table, such as a <div>
. Initially, moving the margin-bottom
to that container was attempted, but it did not work due to the parent elements also establishing a BFC. Alternatively, JavaScript could be used to dynamically add a class with margins to non-empty tables, although this solution may not be preferred.
table { margin-bottom: 1em }
<table><tr><td>1</td></tr></table>
<table><tr><td>2</td></tr></table>
<table><tr><td></td></tr></table>
<table><tr><td>3</td></tr></table>