How to use CSS in Lightning Web Component?

The beauty of Lightning Component Framework is the uniform UI which is consistent in Lightning Design System. So, the styles of Custom Lightning Component and Standard Lightning Component are in uniform. All elements using lightning namespace use Lightning Design System. Also, you can provide slds (Salesforce Lightning Design System) in class attribute of any custom element. Now, we can build the CSS file to provide custom styles for the elements mentioned in the html file.

We can consider the first Lightning Web Component named “welcomeWindow“. Now, we will apply the styles for the welcome content.

Step 1: Need to update the welcomeWindow.js-meta.xml to set the visibility in Lightning App Builder.

welcomeWindow.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="welcomeWindow">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Step 2: Need to update the welcomeWindow.html file.

welcomeWindow.html

<template>
    <lightning-card title="Welcome My Friends">    
        <lightning-layout>
                <lightning-layout-item flexibility="auto" padding="around-small">                    
                        Welcome to LWC Training Class
                </lightning-layout-item>
            </lightning-layout>
    </lightning-card>     
</template>

Step 3: Create a CSS file named “welcomeWindow.css” under welcomeWindow folder.

welcomeWindow.css

.contentClass{
    color:green;
    font-weight: bold;
}

.messageClass{
    border-top: 1px solid #ccc;
    width:100%;
}

Step 4: Again, we have updated welcomeWindow.html file.

welcomeWindow.html

<template>
    <lightning-card title="Welcome My Friends">        
         <div class="messageClass">    
            <lightning-layout>
                    <lightning-layout-item flexibility="auto" padding="around-small">                        
		        <div class="contentClass">                   
                            Welcome to LWC Training Class
                        </div>
                    </lightning-layout-item>
            </lightning-layout>
        </div>
    </lightning-card>     
</template>

Here, we have used messageClass to define the header border and contentClass to define the color of content from the CSS file.

Result

99,612 total views, 60 views today

Rating: 3.8/5. From 16 votes.
Please wait...
This entry was posted in Lightning Web Component. Bookmark the permalink.

Leave a Reply