By default, when using the <lightning-radio-group>
tag in a Lightning Web Component (LWC), the options are displayed vertically. In this article, we will learn how to align a radio group horizontally in LWC.
Step 1: Create a Custom CSS File
To align the radio buttons horizontally, we first need to create a custom CSS file and upload it as a static resource. Copy the following CSS code, create a file named radioButtonHorizontalStyle.css
, and upload it to Salesforce as a static resource.
.customRadioCls .slds-form-element__control .slds-radio { display: inline-block !important; }
Step 2: Write the HTML Code
Once the CSS file is uploaded, we will create an LWC component named RadioButtonGroupHorizontalAlign
and apply the custom styling.
<template> <lightning-card title="Radio Button Horizontal Example"> <div class="slds-p-around_medium"> <lightning-radio-group class="customRadioCls" options={options} name="radioGroup" label="Gender"> </lightning-radio-group> </div> </lightning-card> </template>
Step 3: Load the CSS Dynamically in JavaScript
In the JavaScript file, we will define the radio button options and load the CSS file dynamically using the renderedCallback
lifecycle hook.
import { LightningElement } from 'lwc'; // Importing the static resource that contains CSS for styling the radio buttons import radioButtonHorizontalStyle from '@salesforce/resourceUrl/radioButtonHorizontalStyle'; // Importing the function to load external styles dynamically import { loadStyle } from 'lightning/platformResourceLoader'; export default class RadioButtonGroupHorizontalAlign extends LightningElement { // Defining options for the radio button group options = [ { label: 'Male', value: 'Male' }, { label: 'Female', value: 'Female' } ]; // Lifecycle hook that runs after the component is rendered renderedCallback() { // Dynamically loading the CSS file for horizontal alignment of radio buttons Promise.all([ loadStyle(this, radioButtonHorizontalStyle) ]); } }
Here is the output which you will see when you place the component in a lightning app page.

Why Use renderedCallback?
The renderedCallback
lifecycle hook is executed after the component is inserted into the DOM. Since the CSS file is stored as a static resource, it needs to be loaded dynamically at runtime. By using renderedCallback
, we ensure that the styles are applied only after the component is rendered. This prevents any potential issues where the styles might not be available when the component initially loads.
By following these steps, you can successfully align a radio group horizontally in LWC, ensuring better usability and an improved UI experience.
We hope now you know How to align radio group horizontally in LWC. If you have any doubts then let us know in the comment box below.