2

Situation

I'm building a table row LWC to separate and encapsulate some logic like so:

<!-- tableComp.html -->
<table class="slds-table slds-table_cell-buffer slds-table_bordered">
    <thead>
        <tr class="slds-line-height_reset">
            <th scope="col">Id</th>
            <th scope="col">Name</th>
        </tr>
    </thead>
    <tbody>
        <template for:each={rows} for:item="row">
            <c-row-comp key={row.Id} row={row}></c-row>
        </template>
    </tbody>
</table>

.

<!-- rowComp.html -->
<template>
    <th>
        {row.Id}
    </th>
    <td>
        {row.Name}
    </td>
</template>

.

/* rowComp.css */
:host {
    display: table-row;
}

Problem

SLDS styles are not correctly cascading to the child component, for example, SLDS has this entry to correctly style rows and cells:

.slds-table_cell-buffer tr>th:first-child, 
.slds-table_cell-buffer tr>td:first-child, 
.slds-table--cell-buffer tr>th:first-child, 
.slds-table--cell-buffer tr>td:first-child {
    padding-left: 1.5rem;
}

However since I'm using a component for the row I have the <c-row-comp> element in between therefore the styles are not applied in the child component. Rendered output looks like:

<table class="slds-table slds-table_cell-buffer slds-table_bordered">
    <thead>
        <tr class="slds-line-height_reset">
            <th scope="col">Id</th>
            <th scope="col">Name</th>
        </tr>
    </thead>
    <tbody>
        <c-row-comp>
            <th>X</th>
            <td>Y</td>
        </c-row>
    </tbody>
</table>

Is there a way so that CSS cascades throw the child component so the styling defined in SLDS is respected?

1 Answer 1

2

From the LWC docs:

CSS styles defined in a parent component don’t leak into a child. In our example, a p style defined in the todoApp.css style sheet doesn’t style the p element in the c-todo-item component, because the styles don’t reach into the shadow tree. See CSS.

This is an intentional and fundamental principle for building reusable web components - they encapsulate their own presentation.

You should however be able to make your child element accept the additional classes as an attribute...

RowComp.html

<template>
    <th class={additionalClass}>
        {row.Id}
    </th>
    <td class={additionalClass}>
        {row.Name}
    </td>
</template>

And RowComp.js

export default class RowComp extends LightningElement {
    @api additionalClass = '';
}

You must log in to answer this question.

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