Apply Custom CSS Style to Lightning Data Table In Salesforce LWC

Hey guys, today in this post we are going to learn about applying custom CSS style to lightning data table <lightning-datatable> component in lightning web component [lwc].

Let’s create a scenario :

Requirement : In lightning data table, based on account phone number we need to set row background color. if account phone number field is blank(undefined) then set color as red, else green.

Problem : In LWC, for lightning data-table or lightning tree grid base components we can’t define our style in CSS file [.css]. because once the component get rendered on DOM framework will automatically add web component name as a attribute selector with your CSS class . check following screenshot :

lwc issue for datatable CSS

And in following screenshot as you can see framework is adding lwc name as attribute only for root level component not for each <td> or <th>.

lwc datatable DOM view

 

due to this behavior your .CSS file style will not apply to data-table columns .

Let’s see a solution for it : 

Step 1 : Create a New Apex Class

Apex Class [lightningDataTableLwcController .cls]

  • Apex class to query and return list of account records.

Step 2 : Create a Lightning Web Component

  1. In Visual Studio Code, open the Command Palette by pressing Ctrl+Shift+P (Windows) or Cmd+Shift+P (macOS).
  2. Type sfdx and Select SFDX: Create Lightning Web Component.
  3. Enter lightningDataTablefor the name of the new component and Press Enter.

Copy and paste the following code and save the file.

LWC HTML File [lightningDataTable.html]

LWC JS File : [lightningDataTable.js]

  • Check code comments

LWC Meta XML file [lightningDataTable.js-meta.xml]

Deploy LWC Folder To Org :

  1. Right-click the lightningDataTable folder.
  2. Click SFDX: Deploy Source to Org.

Output :

lwc lightning datatable CSS sfdcmonkey

Please let us know if this post help you 🙂

Related Resource :

Other popular lwc Posts :

Follow us for new post updates. & Don’t forget to bookmark this site for your future reference.

Facebook : https://www.facebook.com/sfdcmonkey/

Instagram : https://www.instagram.com/sfdc_monkey/

Buy me a coffeeBuy me a coffee

(Visited 2,785 times, 1 visits today)

2 thoughts on “Apply Custom CSS Style to Lightning Data Table In Salesforce LWC”

Leave a Comment