Skip to content

Resizable Table Columns in HTML, CSS, JavaScript

Reading Time: < 1 minute

JavaScript is one of the best tools among web developers for creating a customized look and feel in web applications. To create resizable columns in HTML and CSS that behave similarly to Excel, you can use a combination of HTML, CSS, and a bit of JavaScript. Here’s a basic approach

HTML Code

It contains a basic table structure with headers (<th>) and data cells (<td>).

    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th>Column 1</th>
                    <th>Column 2</th>
                    <th>Column 3</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Data 1</td>
                    <td>Data 2</td>
                    <td>Data 3</td>
                </tr>
                <!-- Add more rows as needed -->
            </tbody>
        </table>
    </div>

CSS Code

Provides basic styling, including border, padding, and cursor styles for headers.

.table-container {
    overflow-x: auto;
    width: 100%;
    max-width: 600px; /* Set max width or adjust as needed */
}

table {
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed;
}

th, td {
    border: 1px solid #ccc;
    padding: 8px;
    text-align: left;
}

th {
    background-color: #f2f2f2;
    cursor: col-resize; /* Cursor changes to resize when hovering over headers */
}

JavaScript Code

Implements the resizable functionality. When a user clicks and drags on a header (<th>), it calculates the new width based on mouse movement (mousemove event) and adjust the column width accordingly.

const resizableTable = document.querySelector('table');
let column, startX, startWidth;

function initResizableColumns() {
    const resizableHeaders = resizableTable.querySelectorAll('th');
    resizableHeaders.forEach(header => {
        header.addEventListener('mousedown', function(event) {
            column = event.target.closest('th');
            startX = event.pageX;
            startWidth = parseInt(getComputedStyle(column).width, 10);
            document.addEventListener('mousemove', resizeColumn);
            document.addEventListener('mouseup', stopResize);
        });
    });
}

function resizeColumn(event) {
    const width = startWidth + event.pageX - startX;
    column.style.width = width + 'px';
}

function stopResize() {
    document.removeEventListener('mousemove', resizeColumn);
}

initResizableColumns();

Live in Action

See also  Convert HTML Table to Excel in JavaScript

Leave a Reply