Created
March 25, 2021 17:42
-
-
Save adityanaag3/62e4aecc718db9e9aefb7a9d0d8ede8d to your computer and use it in GitHub Desktop.
Style LWC by assigning the value of a JS Public Property to a CSS Custom Property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
lightning-card{ | |
--my-color: black; | |
} | |
div{ | |
padding: 0.5rem; | |
margin-bottom: 0.5rem; | |
} | |
.myClass { | |
color: var(--my-color); | |
} | |
.myOtherClass { | |
border: 1px solid; | |
border-color: var(--my-color); | |
} | |
.myBadge{ | |
--sds-c-badge-color-background: var(--my-color); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<lightning-card title="JS Properties in CSS"> | |
<div class="container"> | |
<div class="myClass"> | |
Some colored text. | |
</div> | |
</div> | |
<div class="myOtherClass"> | |
Text with border | |
</div> | |
<div class="myBadge"> | |
<lightning-badge label="Badge Base Component"> | |
</lightning-badge> | |
</div> | |
</lightning-card> | |
</template> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { LightningElement, api } from "lwc"; | |
export default class JsInCss extends LightningElement { | |
@api customColor; | |
renderedCallback() { | |
this.template | |
.querySelector("lightning-card") | |
.style.setProperty("--my-color", this.customColor); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment