Sub topic 4
Spacing, typography and utility classes
SLDS ships hundreds of small, single-purpose CSS classes called utility classes. Each one sets one property, such as a margin, a font size or a text color. You combine them in your template instead of writing a stylesheet. This chapter covers the spacing and typography families, how they behave in Lightning web components, and the mistakes that cause most problems.
It assumes you can read a component's HTML template and JavaScript class. It also assumes you know what a Lightning base component is, from the earlier chapters. You need a Salesforce org or scratch org to see the results, because the SLDS stylesheet is supplied by the Lightning page.
How utility class names are built
Spacing class names follow one pattern: property, direction, then size.
slds-m-top_smallmeans margin on the top edge, small size.slds-p-around_mediummeans padding on all four sides, medium size.slds-var-m-bottom_largeis the same pattern withvar-added afterslds-.
The parts are:
| Part | Values | Meaning |
|---|---|---|
| Property | `m`, `p` | Margin (space outside the element) or padding (space inside it) |
| Direction | `top`, `right`, `bottom`, `left`, `horizontal`, `vertical`, `around` | Which edges get the spacing |
| Size | `xxx-small`, `xx-small`, `x-small`, `small`, `medium`, `large`, `x-large`, `xx-large` | A step on a fixed scale |
Note the underscore before the size. Writing slds-m-top-small with a hyphen matches nothing, and the page shows no error. Direction is joined to the property with a hyphen, and size is joined to the direction with an underscore.
The `var` variants
Salesforce added a second set of spacing classes with var in the name, for example slds-var-m-around_medium. These read their values from CSS custom properties (variables), so the spacing can follow a user's display density setting. Salesforce recommends the var form for new code, and the examples in this tutorial use it.
The older classes without var still work. Use one form consistently within a component so the spacing scale stays predictable.
<template>
<div class="slds-var-p-around_medium">
<lightning-input label="City"></lightning-input>
<lightning-button
class="slds-var-m-top_small"
label="Search"
></lightning-button>
</div>
</template>The wrapper div pads all four sides. The button gets space above it, so it does not touch the input.
Margin or padding
Choosing between margin and padding is the most common spacing decision.
- Use padding on a container to create breathing room between its edge and its content. A background color or border stays outside the padding.
- Use margin on an item to separate it from its neighbors.
A practical rule is to put spacing on the child that needs separation and leave the parent alone. Between a stack of siblings, put slds-var-m-top_small on every element except the first. Putting slds-var-m-bottom_small on each one leaves an extra gap under the last.
Vertical margins from adjacent block elements can collapse into one. If a paragraph with a bottom margin sits above one with a top margin, the browser uses the larger value, not the sum. Padding never collapses. If your spacing looks smaller than the classes suggest, collapsed margins are the likely cause.
Applying classes to base components
You can put a utility class on a base component's tag, as in <lightning-button class="slds-var-m-top_small">. The class lands on the host element, the outer lightning-button tag. Margin on the host works, because the host takes part in your layout.
You cannot reach inside the base component. A class on the host does not restyle the button's internal elements, since they live in its shadow DOM. A later chapter covers that boundary and the styling hooks that cross it. For now, treat the host as the only element you can space.
The lightning-card example from the chapter plan shows both cases:
<template>
<lightning-card title="Contact search" icon-name="standard:contact">
<lightning-button
slot="actions"
label="Clear"
onclick={handleClear}
></lightning-button>
<div class="slds-var-p-around_medium">
<lightning-input
type="search"
label="Name"
value={searchKey}
onchange={handleChange}
></lightning-input>
</div>
</lightning-card>
</template>The card body has no padding of its own. The div supplies it. Without the wrapper, the input sits flush against the card edges.
Typography classes
Typography utilities set font size, weight, color and alignment. These are the ones you will use most:
| Class | Effect |
|---|---|
| `slds-text-heading_large` | Large heading text, about 1.75 rem |
| `slds-text-heading_medium` | Medium heading text |
| `slds-text-heading_small` | Small heading text |
| `slds-text-title` | Small label-like title text |
| `slds-text-title_caps` | Uppercase title text, used for column-like labels |
| `slds-text-body_small` | Smaller body text |
| `slds-text-color_weak` | Lighter gray text for secondary information |
| `slds-text-color_error` | Red error text |
| `slds-text-color_success` | Green success text |
| `slds-text-align_center` | Centers text |
| `slds-truncate` | Cuts overflowing text to one line and adds an ellipsis |
A heading class changes how text looks, not what it is. Use the right HTML element for the meaning and a class for the appearance:
<template>
<div class="slds-var-p-around_medium">
<h2 class="slds-text-heading_medium">Account summary</h2>
<p class="slds-text-color_weak slds-var-m-top_x-small">
Last reviewed by the support team.
</p>
<p class="slds-var-m-top_small slds-truncate" title={fullNote}>
{fullNote}
</p>
</div>
</template>Here the h2 keeps heading semantics for screen readers, and slds-text-heading_medium sets its size. The slds-truncate paragraph needs a width limit from its parent to truncate anything. The title attribute lets a sighted mouse user read the full text on hover.
Do not use a heading class on a div to fake a heading. Assistive technology then sees no heading, and the page outline breaks.
Other common utilities
A few non-spacing utilities appear in almost every component:
slds-hideandslds-showsetdisplay: noneanddisplay: block. They hide content from everyone, including screen readers.slds-assistive-texthides content visually but keeps it readable by screen readers. Use it for labels you want read aloud but not displayed.slds-is-relativesetsposition: relative. It is often the parent for a spinner placed over a region.
Prefer the lwc:if directive to slds-hide when content is expensive to render. A hidden element still exists in the DOM, so its component still loads and runs.
Combining classes dynamically
The class attribute in an LWC template takes a static string. You cannot write class={someExpression} with partial strings or inline logic like class="slds-m-top_{size}". Compute the full string in a getter instead:
import { LightningElement, api } from 'lwc';
export default class StatusNote extends LightningElement {
@api isError = false;
get noteClass() {
return this.isError
? 'slds-var-m-top_small slds-text-color_error'
: 'slds-var-m-top_small slds-text-color_weak';
}
}<template>
<p class={noteClass}>Check the highlighted fields.</p>
</template>The getter returns whole class names, so the SLDS stylesheet matches them. Building a name from fragments, such as 'slds-m-top_' + size, works at runtime. It is harder to search for later and easy to get wrong, so keep full class names in the source.
Common errors
- A class has no effect. Check the underscore and hyphen placement first. Then check whether you put it on an element inside a base component's shadow DOM, where it cannot reach.
- Spacing is missing in Jest tests or a local preview. The SLDS stylesheet comes from Lightning Experience. Jest does not load it, so tests cannot check visual spacing.
- Mixed spacing scales. Combining
slds-m-*andslds-var-m-*on one element is allowed but makes the effective value hard to predict. Pick one family per element. - Overriding a utility with your own CSS. If you write
.my-box { margin-top: 4px; }and also addslds-var-m-top_small, the winner depends on specificity and load order. Choose one source.
Exercise
A developer writes <lightning-button class="slds-m-top-small" label="Save"> and sees no gap above the button. What are two things wrong or worth changing, and what is the corrected tag?
Show answer
The class name uses a hyphen between direction and size, but SLDS requires an underscore, so slds-m-top-small matches nothing. The recommended family for new code is the var form. The corrected tag is <lightning-button class="slds-var-m-top_small" label="Save">.
Exercise
You need a heading that looks like slds-text-heading_large but must appear as a level 2 heading in the page outline. Which element do you write, and why not use a div?
Show answer
Write <h2 class="slds-text-heading_large">...</h2>. The h2 element gives screen readers and the page outline a real level 2 heading. A div with the class would look the same but carry no heading meaning.