Vertically center LWC lightning-button icons to the button text

csslightning-buttoniconlightning-web-componentsslds-styling-hooks

LWC lightning-button icons are too low relative to button label. For example…

<lightning-button-group class="slds-m-top_x-small slds-m-bottom_x-small slds-align_right">
  <lightning-button label="Add" icon-name="utility:add"></lightning-button>
  <lightning-button label="Delete Selected" icon-name="utility:delete"></lightning-button>
</lightning-button-group>

enter image description here

Odd that Salesforce does not vertically-align icons with the button label.

To override the behavior, I would normally do something like this…

svg.slds-button__icon {
  position: relative;
  top: -2px;
}
/* or... */
svg.slds-button__icon {
  margin-bottom: 4px;
}

The Local Development Server appears to strip this out (and I know restyling slds classes is not recommended per the docs).

Styling hooks appear to be the recommended way to do it but…

  1. Setting a custom CSS variable on :host breaks the Local Development Server. This seems to be a known issue Salesforce is unwilling to fix and I'm not sure how to workaround that problem.
  2. Even if #1 worked, I am not seeing categories and properties for --slds-c-icon- that let me set the bottom margin or make the icon a relative position.

Do I need to create my own component based on the template for the lightning-button or is there an easier way to get the result I want?

Best Answer

You can use CSS custom properties to override the styles for the lightning-button component. Custom properties are part of the CSS spec and are scoped to the component.

Here's how you could adjust the position of the icon relative to the label:

<template>
  <lightning-button label="Add" icon-name="utility:add">
  </lightning-button>
</template>

<style>
  lightning-button {
    --lwc-button__icon-position: relative;
    --lwc-button__icon-bottom: 4px;
  }
</style>

You can find the list of available CSS custom properties for lightning-button in the Lightning Web Components documentation.

Note that customizing the styles of a standard component can impact the look and feel of your app, so it's important to consider the consequences of doing so and whether it's necessary for your particular use case.

Related Topic