Saturday, December 12, 2020

How to add styling to Lightning Web Component?

  In this blog post we will see "How to add styling to Lightning Web Component".

1) To apply styling to component we create style sheet in the component's folder as shown below.

How to add styling to Lightning Web Component

2) The name of the style sheet is same as that of components and it use standard CSS syntax.

3) Each component can have only one style sheet and they cannot share the style sheet.

4) When we define a style sheet for a component in a component folder it is limited to that component only and this avoid loosing the style sheet of the component when we reuse this component in different contexts. This also avoid component style sheet getting override in other part of the page.

5) When we render a component the <template> tag in HTML file is replaced with <namespace-component-name>. For example a component with the temaplte myTest.html in example namespace will render as <example-my-test>.

6) In case if we have parent child components the style sheet of the parent will not apply to child component as shown in below example.

myComponentParent.html

<template>
    <p>
      I am Parent Comp HTML file.
    </p>
     <c-my-component-child></c-my-component-child>
 </template>


myComponentParent.js

import { LightningElement } from 'lwc';

export default class MyComponentParent extends LightningElement {}


myComponent.css

p {
    font-size: x-large;
}


myComponentChild.html


<template>
    <p>
      I am Child Comp HTML file.
    </p>
     
 </template>


myComponentChild.js

import { LightningElement } from 'lwc';

export default class MyComponentChild extends LightningElement {}


myComponentChild.css

/*
p {
    font-size: x-large;
}
*/


testApp.app

<aura:application>
<c:myComponentParent></c:myComponentParent>
</aura:application>


OUTPUT:



How to add styling to Lightning Web Component




7) A parent component can style a child component but it style it as an single element and it does not reach into the DOM of a child as shown in below example.


myComponentParent.css

p {

    font-size: x-large;

}

c-my-component-child {

    font-size: xx-large;

}


OUTPUT:


How to add styling to Lightning Web Component

No comments:

Post a Comment