Component CSS Style Sheet Creation

By in
379
Component CSS Style Sheet Creation

Create a style sheet in the component’s folder to provide styles with the component. The component and sheet need to share the same name. The style sheet is automatically applied to the component. Let’s dive in and review how style sheets, parent components, and child components relate to each other.

First, here can only be one style sheet per component. They support the majority of selectors and use standard CSS syntax. Style rules from various CSS modules can be imported into a style sheet.

A component’s style sheet determines which styles are applicable to it. Following this criteria, a component can be utilized multiple times without losing its style. Additionally, it stops a component’s styles from superseding those in other pages’ components.

This illustration shows how a child component is not affected by the CSS styles defined in the parent component. The two parts are c-parent and c-child. An “h1” tag appears on each element. The h1 style is designated as xx-large in the parent.css style sheet. When you run the code, the style only affects the parent’s h1> tag and not the nested child’s h1> tag.

 

<!– parent.html –>

<template>

<h1>To Do List (h1)</h1>

<c-child></c-child>

</template>

 

/* parent.css */

h1 {

font-size: xx-large;

}

 

<!–- child.html–>

<template>

<h1>To Do Item (h1)</h1>

</template>

 

Style Sheet and Parent Component
Image Source: Salesforce

 

Although it styles it as a single element, a parent component can style a child component. A parent is unable to enter a child. Let’s provide the parent a c-child selector. CSS that specifies the child component’s border.

 

/* parent.css */

h1 {

font-size: xx-large;

}

 

c-child {

display: block;

border: 2px solid red;

}

 

Style Sheet and Parent Component

 

Let’s now style the c-child component using child.css, which is its own style sheet.

Let’s delete the c-child selector from parent.css in order to remove the red box before we add a selector to child.css. Because it might be confusing and provide unexpected outcomes, styling components from both the component and its parent is not a smart practice. Take a look at parent.css without the c-child.

 

/* parent.css */

h1 {

font-size: xx-large;

}

 

The style sheet for a component can style its own element, in this case c-child.

 

Conclusion

In this way, we can add different CSS styles to any Lightning Web Component.

 

To learn more about Lightning Web Components, check out some of my related blogs below!

 

Additional Resources

Cover Photo by Kelly Sikkema on Unsplash

Leave a reply

Your email address will not be published. Required fields are marked *