Lightning Web Component

How to Style Lightning Datatable using CSS

Lightning Datatable in Salesforce allows you to display tabular data with rich features and functionalities. While its default styling fits well within the Salesforce Lightning Design System, there might be cases where you want to customize the appearance of the datatable to align with your brand or user interface requirements.

Style Lightning Datatable with CSS

Style Lightning Datatable

To add a style to your custom Lightning Datatable in your LWC, you'll need to use CSS classes. Salesforce allows you to leverage its built-in CSS classes or define your own to target specific elements within the datatable.

Apply the CSS Class to Datatable

<lightning-datatable
    data={data}
    columns={columns}
    key-field="id"
    class="custom-datatable-style"
></lightning-datatable>

Modifying Styles using JavaScript

To override the default CSS of a Lightning Datatable, you can make use of JavaScript in the renderedCallback() lifecycle method. This approach empowers you to make dynamic adjustments to the component's styling.

In this example we're going to change only styles of the last row of the table(could be useful to display totals), the renderedCallback() function generates a <style> element and appends it to the .custom-datatable-style class, effectively customizing the appearance of the last row in the datatable.

Style Lightning Datatable with totals highlighted
import { LightningElement } from 'lwc';

export default class ExampleComponent extends LightningElement {

    renderedCallback(){
        let styles = document.createElement('style');
        styles.innerText = '.custom-datatable-style tr:last-child, .custom-datatable-style tr:last-child > th {font-weight: bold;color:inherit;text-decoration:none;pointer-events:none;background-color:rgb(243, 243, 243)}';
        this.template.querySelector('.custom-datatable-style').appendChild(styles);
    }

}

Alternate the Background Color of Rows

This example demonstrates what you should add to the renderedCallback() to alternate the colors of each rows to style datatable

Datatable style with different colors
renderedCallback(){
    let styles = document.createElement('style');
    styles.innerText = '.custom-datatable-style tbody tr:nth-child(even) { background-color: #60D2FF; } .custom-datatable-style tbody tr:nth-child(odd) { background-color: #a4e3fb; }';
    this.template.querySelector('.custom-datatable-style').appendChild(styles);
}

Changing the Background Color of a Column

Here you'll have to change the td:nth-child({number of column}) specifying the number of column that you need to change:

Lightning Datatable with different colors per columns
renderedCallback(){
    let styles = document.createElement('style');
    styles.innerText = '.custom-datatable-style tbody tr th {background-color: #60D2FF;}';
    this.template.querySelector('.custom-datatable-style').appendChild(styles);
}