Target inner elements of standard Lightning Web Components with CSS

Say we have a LWC with the following template in a component named example:

<template>
    <lightning-textarea class="test"></lightning-textarea>
</template>

And some css to go with it:

.test textarea {
    min-height: 500px;
}

The expected behavior is that the lightning-textarea will be 500px tall because the nested textarea has been made 500px tall.

The actual behavior is that nothing happens. The reason for this is that the compiled css will be:

.test[c-example_example] textarea[c-example_example] {
    min-height: 500px;
}

And the compiled (relevant parts of the) html will be:

<lightning-textarea c-example_example lightning-textarea_textarea class="test"> 
   <textarea lightning-textarea_textarea></textarea>
</lightning-textarea>

It’s obvious that the CSS Module Scoping has scoped the textarea element to its parent, lightning-textarea and not our example component. This is an issue because the CSS processor has appended [c-example_example] not only to the .test part of the selector, but textarea as well.

It makes sense that CSS would be scoped downward, which is how Aura components handled scoping, but in LWC it’s actually entirely isolated, so neither parent nor child elements can target it.

Is there any way around this? Or plans to support targeting child components? Being able to override and tweak the CSS of the standard component library was a very handy feature of Aura components, allowing customized appearances without having to rewrite the base component from scratch.

On top of that, this means that you can’t reuse your own components in different contexts, giving them different styles in each. The component itself must be responsible for all of its styling. While this is possible it requires a lot of conditional class assignments which is frustrating.

Answer

As of Winter `21, you can use styling hooks (beta): https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.create_components_css_custom_properties

Attribution
Source : Link , Question Author : Benjamin Vogler , Answer Author : Jody Bleyle

Leave a Comment