Border doesn't adapt after collapsing a column

For my main project, I’m trying to find a way to hide a column in JS. The following function :

function hide() {
    const table = document.getElementById('test');
    const cols = table.getElementsByTagName('col');
    cols[1].style.visibility = "collapse";
}

works great, but the borders don’t move. Here’s the problem :
first image becomes second image

How can I avoid this issue ?

EDIT : This works as intended on Chrome and Edge. Is this a bug for Firefox?

Full html is:

function hide() {
    const table = document.getElementById('test');
    const cols = table.getElementsByTagName('col');
    cols[1].style.visibility = "collapse";
}
table, tr, th, td {
    border: 1px solid;
    border-collapse: collapse;
}
<table id="test">
    <colgroup>
        <col><col><col>
    </colgroup>
    <tr>
        <th>1</th>
        <th>2</th>
        <th>3</th>
    </tr>
    <tr>
        <td>un</td>
        <td>deux</td>
        <td>trois</td>
    </tr>
    <tr>
        <td>one</td>
        <td>two</td>
        <td>three</td>
    </tr>
</table>

<button onclick=hide()>Hide</button>

>Solution :

The issue with the border not adapting after collapsing a column is due to the use of the border-collapse: collapse; property in the CSS. When you collapse a column, the remaining columns are not automatically adjusted to fill the empty space.

To address this issue, you can use the border-spacing property instead of border-collapse. Modify your CSS as follows:

<style>
table {
    border-spacing: 0;
}

th, td {
    border: 1px solid;
    padding: 5px; /* Optional: Add padding to th and td elements for better spacing */
}
</style>

With this change, the border will adapt properly when a column is collapsed. Additionally, you can add padding to th and td elements for better spacing, as shown in the example.

Leave a Reply