Sub topic 5
Cell alignment and styling with cellAttributes
This chapter assumes you have a working lightning-datatable with a columns array, a data array, and a key-field. It also assumes you are comfortable with JavaScript object spread and with wired Apex methods. If any of that is unfamiliar, review the earlier chapters on columns and loading data first.
Column types control how a value is formatted. They do not control how a cell looks. The cellAttributes property of a column definition covers that: alignment, CSS classes, and icons. This chapter explains what it accepts, how to make it depend on each row's data, and where it stops working.
What cellAttributes is
cellAttributes is an object on a column definition. The table applies its values to every cell in that column. Each value is either fixed for the whole column or read from the row.
| Attribute | Purpose | Example value |
|---|---|---|
| `alignment` | Horizontal alignment of the cell content | `'left'`, `'center'`, `'right'` |
| `class` | CSS classes added to the cell | `'slds-text-color_weak'` |
| `iconName` | An SLDS icon shown in the cell | `'utility:warning'` |
| `iconLabel` | Text shown next to the icon | `'Missing email'` |
| `iconPosition` | Which side of the content the icon sits on | `'left'`, `'right'` |
| `iconAlternativeText` | Text read by screen readers for the icon | `'Warning'` |
Because cellAttributes belongs to the column, you set it next to label, fieldName, and type. It is separate from typeAttributes, which configures how the type itself formats the value, such as a date's year and month options.
Fixed alignment
A fixed alignment is a plain string in cellAttributes. Text columns align to the left. Numeric types such as number, currency, and percent align to the right by default. Setting alignment overrides either default.
const COLUMNS = [
{ label: 'Name', fieldName: 'Name', type: 'text' },
{
label: 'Phone',
fieldName: 'Phone',
type: 'phone',
cellAttributes: { alignment: 'center' }
},
{
label: 'Birthdate',
fieldName: 'Birthdate',
type: 'date-local',
cellAttributes: { alignment: 'right' }
}
];Pick one alignment rule per kind of data and apply it consistently. Right-aligned numbers line up by digit, which makes them easier to compare. Left-aligned text is easier to scan. Centering suits short, uniform values such as status flags or icons.
Fixed classes
The class attribute accepts a string of one or more class names separated by spaces. The table adds them to the cell.
{
label: 'Email',
fieldName: 'Email',
type: 'email',
cellAttributes: { class: 'slds-text-color_weak' }
}Use Salesforce Lightning Design System (SLDS) utility classes here. They are already loaded on the page and are the supported way to style a datatable. Some useful ones are:
slds-text-color_success,slds-text-color_error, andslds-text-color_weakfor text color.slds-text-title_capsfor uppercase small text.slds-text-heading_smallfor larger text.slds-theme_shadeand otherslds-theme_*classes for background tints.
Styling that depends on the row
A fixed value treats every row the same. To vary a cell by row, replace the value with an object that has a fieldName property. The table then reads the value from that field of each row object, in the same way a column's own fieldName works.
{
label: 'Name',
fieldName: 'Name',
type: 'text',
cellAttributes: {
class: { fieldName: 'nameClass' },
iconName: { fieldName: 'nameIcon' },
iconPosition: 'left',
iconAlternativeText: 'Missing email'
}
}The fields nameClass and nameIcon do not exist on the Contact record. You have to add them to each row before you pass data to the table. That makes this a data-preparation step, and it fits naturally in the wired handler from the loading chapter.
A complete example
This component flags contacts that have no email address. It marks their names in the error color and adds a warning icon. It reuses the getContacts Apex method from earlier in the tutorial.
import { LightningElement, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
const COLUMNS = [
{
label: 'Name',
fieldName: 'Name',
type: 'text',
cellAttributes: {
class: { fieldName: 'nameClass' },
iconName: { fieldName: 'nameIcon' },
iconPosition: 'left',
iconAlternativeText: 'Missing email'
}
},
{ label: 'Email', fieldName: 'Email', type: 'email' },
{
label: 'Phone',
fieldName: 'Phone',
type: 'phone',
cellAttributes: { alignment: 'center' }
},
{
label: 'Birthdate',
fieldName: 'Birthdate',
type: 'date-local',
cellAttributes: { alignment: 'right' }
}
];
export default class ContactTable extends LightningElement {
columns = COLUMNS;
data = [];
error;
wiredResult;
@wire(getContacts)
wiredContacts(result) {
this.wiredResult = result;
const { data, error } = result;
if (data) {
this.data = data.map((contact) => this.decorate(contact));
this.error = undefined;
} else if (error) {
this.error = error;
this.data = [];
}
}
decorate(contact) {
const missingEmail = !contact.Email;
return {
...contact,
nameClass: missingEmail ? 'slds-text-color_error' : undefined,
nameIcon: missingEmail ? 'utility:warning' : undefined
};
}
}<template>
<lightning-card title="Contacts" icon-name="standard:contact">
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
hide-checkbox-column>
</lightning-datatable>
</lightning-card>
</template>Several details in this code matter:
decoratereturns a new object with the spread operator. The records that a wire delivers are read-only, so you cannot assigncontact.nameClassdirectly.nameClassandnameIconareundefinedfor contacts that have an email. A row with no value for the field gets no class and no icon, so you do not need an "empty" class.iconPositionandiconAlternativeTextare fixed for the column. Only the values that really differ between rows need afieldName.- When
refreshApexruns, the wire handler runs again and appliesdecorateto the fresh records, so the styling stays correct after a save.
Constraints and common errors
Your component's CSS does not reach the cells. The datatable renders its cells inside its own shadow DOM. A rule such as .highlight { background: yellow; } in your component's .css file will not match them, even if you name that class in cellAttributes. Use SLDS utility classes, or build a custom column type when you need styling that SLDS does not offer. The final chapter covers custom types.
The derived field is missing. If you write class: { fieldName: 'nameClass' } but your rows have no nameClass, the table shows no error and applies no class. When styling does not appear, log one row of data and check that the field name matches exactly, including case.
The class is applied to the cell, not the row. cellAttributes styles individual columns. To tint a whole row you would have to repeat the class on every column. The datatable has no row-level class attribute.
Derived fields are not part of the record. They exist only in the objects you pass to the table. When the user edits a cell inline, the draft values contain Id and the changed fields, not nameClass or nameIcon. You can therefore pass drafts to updateRecord as the saving chapter shows without stripping anything out. If you read selectedRows or row-action rows, however, you receive the decorated objects. Do not send those whole objects to Apex.
Alignment is per column. You cannot align individual cells differently with a static value. If you need that, use an object with fieldName for alignment and put 'left', 'center', or 'right' in the row data. This is unusual and makes the table harder to read, so do it only with a clear reason.
Choosing between the options
- Use fixed
alignmentfor consistent formatting of a whole column. - Use a fixed
classfor styling that is the same in every row, such as muted secondary text. - Use
{ fieldName: '...' }when the style depends on the record's data, such as a status, an overdue date, or a missing value. - Use a custom column type when you need markup, custom CSS, or behavior that a class and an icon cannot provide.
Exercise
A column for Amount__c has cellAttributes: { class: { fieldName: 'amountClass' } }. Your wired handler sets this.data = data; and never adds amountClass. A teammate proposes fixing it with data.forEach(r => { r.amountClass = r.Amount__c < 0 ? 'slds-text-color_error' : ''; }). Why does this fail, and what is the correct approach?
Show answer
Records delivered by a wire are read-only, so assigning a new property to them does not work and can throw an error in strict mode. Build new objects instead: this.data = data.map((r) => ({ ...r, amountClass: r.Amount__c < 0 ? 'slds-text-color_error' : undefined }));. The table then finds amountClass on each row.
Exercise
You add .negative { color: red; } to the component's CSS file and set cellAttributes: { class: 'negative' }. The text stays black. Why, and what should you use instead?
Show answer
The datatable renders its cells in its own shadow DOM, so your component's stylesheet cannot match them. Use an SLDS utility class such as slds-text-color_error, which is already available on the page, or a custom column type if you need styling SLDS does not provide.