Setting Lightning Datatable Width for Horizontal Scrolling?

Setting Lightning Datatable Width for Horizontal Scrolling?

On February 19, 2025, Posted by , In LWC Essentials,Salesforce Technical Questions, With Comments Off on Setting Lightning Datatable Width for Horizontal Scrolling?
Setting Lightning Datatable Width for Horizontal Scrolling

Question

When configuring a related list in a Lightning page, the rendered table has a <div> with a specific width derived from column widths, allowing horizontal scrolling. This prevents columns from being squished while ensuring users can scroll to view all data.

In a custom Lightning Web Component (LWC) using lightning-datatable, how can I achieve the same effect? Using column-widths-mode="auto" does not help, as it sets the width based on the container rather than the table content, which adjusts dynamically on browser resize. The documentation does not provide a clear explanation. How can I set a proper width to ensure smooth horizontal scrolling?

Answer

One approach is to set an initialWidth property for each column while configuring the columns array in JavaScript. This ensures the table width expands based on column widths instead of the container size.

CRS Info Solutions offers expert-led Salesforce training in Hyderabad, covering Admin, Developer (Apex), and Integration to help you excel in the competitive job market. Enroll for free demo today!!!

Here’s an example implementation:

HTML:

<template>
    <div style="height: 300px;">
        <lightning-datatable
            key-field="id"
            data={data}
            columns={columns}>
        </lightning-datatable>
    </div>
</template>

Explanation: The above code defines a lightning-datatable inside a <div> with a fixed height of 300 pixels. The table is populated with data and column definitions from the columns array, ensuring structured display. This setup allows the table to maintain a consistent height while enabling vertical or horizontal scrolling when necessary.

JavaScript:

import { LightningElement } from 'lwc';

const columns = [
    { label: 'Label', fieldName: 'name', initialWidth: 200 },
    { label: 'Website', fieldName: 'website', type: 'url', initialWidth: 200 },
    { label: 'Phone', fieldName: 'phone', type: 'phone', initialWidth: 200 },
    { label: 'Balance', fieldName: 'amount', type: 'currency', initialWidth: 200 },
    { label: 'CloseAt', fieldName: 'closeAt', type: 'date', initialWidth: 200 },
    { label: 'CloseAt1', fieldName: 'closeAt1', type: 'date', initialWidth: 200 },
    { label: 'CloseAt2', fieldName: 'closeAt2', type: 'date', initialWidth: 200 },
];

export default class BaseDatatable extends LightningElement {
    data = [];
    columns = columns;

    connectedCallback() {
        this.data = this.generateData({ amountOfRecords: 100 });
    }

    generateData({ amountOfRecords }) {
        return [...Array(amountOfRecords)].map((_, index) => ({
            name: `Name (${index})`,
            website: 'www.salesforce.com',
            amount: Math.floor(Math.random() * 100),
            phone: `${Math.floor(Math.random() * 9000000000) + 1000000000}`,
            closeAt: new Date(Date.now() + 86400000 * Math.ceil(Math.random() * 20)),
            closeAt1: new Date(Date.now() + 86400000 * Math.ceil(Math.random() * 20)),
            closeAt2: new Date(Date.now() + 86400000 * Math.ceil(Math.random() * 20)),
        }));
    }
}

Explanation: This Lightning Web Component (BaseDatatable) creates a lightning-datatable with predefined columns, each having a fixed initialWidth of 200 pixels to ensure consistent column sizing. The connectedCallback() method populates the table with 100 dynamically generated records, including fields like name, website, phone, amount, and dates. The generateData() function generates sample data using random values and future dates, ensuring the table displays a variety of information for testing or demonstration purposes.

This method ensures each column has a predefined width, preventing the table from shrinking to fit the container. If more columns exist than the available space, horizontal scrolling is enabled automatically.

Alternate Approaches

1. Using CSS for a Fixed Table Width

Another approach is to wrap the lightning-datatable inside a div with overflow-x: auto; and a fixed width. This prevents the table from squeezing to fit within the available space.

HTML:

htmlCopyEdit<template>
    <div style="overflow-x: auto; width: 1200px;">
        <lightning-datatable
            key-field="id"
            data={data}
            columns={columns}>
        </lightning-datatable>
    </div>
</template>

Explanation: This code defines a lightning-datatable inside a div with overflow-x: auto; and a fixed width of 1200px, allowing horizontal scrolling when the table exceeds the container’s width. The key-field="id" ensures each row has a unique identifier, while data={data} and columns={columns} dynamically bind the table’s content and structure. This setup prevents column compression, ensuring a better user experience when viewing large datasets.

Here, setting a fixed width (1200px) on the containing div ensures that the table maintains a proper width for scrolling, regardless of the available screen size.

2. Dynamically Setting Table Width Using JavaScript

If a dynamic solution is needed, the table width can be adjusted at runtime based on the total width of all columns. This can be done using JavaScript after the component renders.

JavaScript:

import { LightningElement } from 'lwc';

export default class DynamicTableWidth extends LightningElement {
    renderedCallback() {
        const tableContainer = this.template.querySelector('.table-container');
        if (tableContainer) {
            tableContainer.style.width = `${this.calculateTableWidth()}px`;
        }
    }

    calculateTableWidth() {
        const columnWidths = [200, 200, 200, 200]; // Example column widths
        return columnWidths.reduce((sum, width) => sum + width, 0) + 50; // Extra padding
    }
}

Explanation: This Lightning Web Component (DynamicTableWidth) dynamically sets the width of a table container based on predefined column widths. In the renderedCallback(), it selects the .table-container element and assigns it a calculated width to ensure proper spacing and scrolling. The calculateTableWidth() method sums the column widths and adds extra padding, preventing the table from being compressed within its container.

HTML:

<template>
    <div class="table-container" style="overflow-x: auto;">
        <lightning-datatable
            key-field="id"
            data={data}
            columns={columns}>
        </lightning-datatable>
    </div>
</template>

Explanation: This template defines a lightning-datatable inside a div with the class table-container, which has overflow-x: auto; to enable horizontal scrolling when needed. The datatable component is dynamically populated with data and columns, ensuring flexible content rendering. This structure prevents column squeezing by allowing users to scroll horizontally if the total column width exceeds the container’s size.

This approach dynamically calculates and sets the table width based on column widths, ensuring horizontal scrolling works correctly even when columns are added or removed.

3. Using slds-scrollable_x for Salesforce Styling

If you prefer using Salesforce’s built-in styling, wrapping the table in a slds-scrollable_x div ensures proper scrolling.

HTML:

<template>
    <div class="slds-scrollable_x" style="width: 100%;">
        <lightning-datatable
            key-field="id"
            data={data}
            columns={columns}>
        </lightning-datatable>
    </div>
</template>

Explanation: This code defines a lightning-datatable inside a div with the class table-container and overflow-x: auto;, enabling horizontal scrolling when the table exceeds the available width. The key-field="id" ensures each row is uniquely identified, while data={data} and columns={columns} dynamically populate the table with records and column definitions. By not setting a fixed width, the container adapts to the table’s content, making it more flexible for different screen sizes.

This method ensures horizontal scrolling follows Salesforce’s Lightning Design System (SLDS) best practices without needing additional styles.

Conclusion

To ensure lightning-datatable maintains a proper width for horizontal scrolling, you can set initialWidth for each column to prevent them from resizing unpredictably. Wrapping the table inside a fixed-width div with overflow-x: auto; allows horizontal scrolling when the content exceeds the container’s width. Another approach is dynamically calculating and setting the table width using JavaScript to match the total column widths. Additionally, using Salesforce’s slds-scrollable_x class provides a built-in styling solution for managing horizontal scrolling effectively.

Each method has advantages depending on whether you want a static, CSS-based, or dynamic JavaScript solution.

Kickstart Your Salesforce Career in Hyderabad’s Thriving IT Hub

Hyderabad has become a major center for IT and cloud computing, with Salesforce playing a key role in transforming businesses. Salesforce training in Hyderabad As companies increasingly adopt Salesforce for CRM, AI, integration, and automation, the demand for skilled professionals is at an all-time high. Leading firms like Deloitte, Accenture, Infosys, TCS, and Wipro actively recruit certified Salesforce experts, making specialized training essential for career growth.

For aspiring professionals, choosing the right training program is crucial. CRS Info Solutions offers comprehensive Salesforce training in KPHB, covering essential modules such as Admin, Developer (Apex), and Integration. With hands-on projects, real-world case studies, and expert-led instruction, this program prepares you for certification and success in Hyderabad’s competitive job market. Take charge of your future—enroll now and start your Salesforce journey!!!

Comments are closed.