Use HTML Templates
Bind Data in a Template
Bind HTML Classes
Bind Inline Styles
Render HTML Conditionally
Render Lists
Render Multiple Templates
TypeScript (Developer Preview)
Mobile-Ready Components
Develop Secure Code
Append a class or multiple classes on an element or component using its style attribute.
1<div class="block" style={inlineStyles}></div>This example uses a getter to set inline styles on an element. To provide multiple styles, separate the styles using a semi-colon. Also, use standard kebab-cased CSS property keys like font-size.
1import { LightningElement } from "lwc";
2
3export default class extends LightningElement {
4 percentage = 80;
5
6 get inlineStyles() {
7 return `width: ${this.percentage}%; font-size: 20px`;
8 }
9}When binding inline styles, follow the style global attribute guidelines. Consider using the class attribute with a stylesheet in your component bundle for reusability first. Using inline styles can be helpful when you need to compute properties to generate different styles based on a condition. For example, this function appends a background color that depends on the value this.iconName.
1get computedStyles() {
2 if (this.iconName) {
3 const color = getIconColor(this.iconName);
4 if (color) {
5 return `background-color: ${color}`;
6 }
7 }
8 const fallbackColor = '#eee';
9 return `background-color: ${fallbackColor}`;
10}Here’s an example that uses an input field to change the size of a chart bar with an inline style. The c-input parent component assigns the percentage property based on user input. It uses the property to pass a value down to the child c-chart component. The child component evaluates the inline style based on the value that’s passed down.
1<!-- c-input -->
2<template>
3 <div>
4 Percentage:
5 <input
6 type="number"
7 min="0"
8 max="100"
9 value={percentage}
10 onchange={handlePercentageChange}
11 ></input>
12 <c-chart percentage={percentage}></c-chart>
13 </div>
14</template>When the number in the input field changes, the handlePercentageChange event handler assigns the new value to this.percentage.
1// c-input
2import { LightningElement } from "lwc";
3
4export default class Input extends LightningElement {
5 percentage = 50;
6
7 handlePercentageChange(event) {
8 const percentage = event.target.value;
9 this.percentage = percentage <= 100 ? percentage : 100;
10 }
11}The c-chart child component displays the percentage value, which is passed down from c-input.
1<!-- c-chart -->
2<template>
3 <div class="container">
4 <div class="text">{percentage}%</div>
5 <div class="bar" style={style}></div>
6 </div>
7</template>c-chart evaluates the inline styles based on the percentage property.
1// c-chart
2import { LightningElement, api } from "lwc";
3
4export default class ChartBar extends LightningElement {
5 @api percentage;
6
7 get style() {
8 return `width: ${this.percentage}%`;
9 }
10}See Also