2

I have two components that have a parent and child relationship. I am trying to apply css from the parent component's css file to the child component without having to write it in multiple places.

Question

  1. How can I use the parent css (parent component) file to style the child component?

Expected results:

  1. Any style set from the parentTree.css should cascade down to the child

Actual results:

  1. No styling is cascaded down to the child

What I tried that didn't work

childTree.html

<template>
        <div class="childTree">
            <template for:each={branches.items} for:item="branch">
                <c-child-tree key={branch.id} branch={branch}></c-child-tree>
            </template>
        </div>
</template>

parentTree.html

<template>
    <div class="parentTree">
        <template for:each={branches} for:item="branch">
           <c-child-tree key={branch.id} branch={branch}></c-child-tree>
        </template>
    </div>
</template>

parent.css

.parentTree, 
.parentTree c-child-tree {
  color: red;
}

c-child-tree .childTree {
  color: blue;
}

2 Answers 2

0

No styling is cascaded down to the child

This is because of the default behavior, the closed Shadow DOM.

In order to allow this behavior, you must make the child component a Light DOM component.

Change the child component's template tag to:

<template lwc:render-mode="light">

And in the ChildTree class, set a static variable, like this:

export default class ChildTree extends LightningElement {
  static renderMode = "light";
  // rest of class
}

This will allow you to apply styles and query child DOM elements.

1
0

Unfortunately CSS styles defined in a parent component aren't able to reach into a child component due to CSS encapsulation in the Shadow Dom. Parent components can only style child components as a single element, for example adding a border around the entire child component. This is detailed in the Docs here: CSS Stylesheets

This means we have two approaches:

  1. As per sfdxfox's answer, utilise Light DOM!
  2. Update the Stylesheet in each component (parent and child)
  3. Create a shared CSS module that you can import into your components. This involves creating a new LWC that only contains a CSS and configuration file before importing this into your other components. There's more detail on doing this here: Share CSS Style Rules
3

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .