1

I am using lightning-input of type number (LWC) and trying to have input text center aligned.

At the end, element's class is being set to "slds-input", So I cannot use custom class to add css.

I am not able to override text-align with css mentioned below. What am I missing? Please help.

<lightning-input
     type="number"
     name="inputNumber"
     class="inputNumberCenter"
     value={answer}
     onchange={handleValueChange}
     step="1">
</lightning-input>


input.slds-input {
    text-align: center
};

Rendered HTML enter image description here

3
  • 1
    You can't do this. LWC uses a shadow DOM to prevent this type of style tampering. You'll have to write your own custom component instead.
    – sfdcfox
    Nov 16, 2019 at 20:24
  • Thank you @sfdcfox
    – Sriram
    Nov 16, 2019 at 21:01
  • Hey Sriram, you just have to override the CSS of the custom component. For that, you have to create a CSS file upload it to static resource and import it in the LWC component using loadstyle. FYI : salesforce.stackexchange.com/questions/278366/… Mar 7, 2022 at 13:07

2 Answers 2

2

After spending a lot of time, the below approach got worked (which is written in connectedcallback method).

Apply input-text-align_right class name to lightning-input tag.

const inputAligncenter = document.createElement('style');
inputAligncenter .innerText = `.input-text-align_right input{ text-align: center!important; }`;
document.body.appendChild(inputAligncenter);
2
  • This worked for me. Jun 22, 2022 at 2:08
  • This worked for me. Thanks! Dec 9, 2022 at 9:23
0

Try to add "slds-align_absolute-center"right afer the slds-input. If it doesn't work to add a div in top:

<div class="slds-align_absolute-center">
 <input lightning-input ....... />
</div>
1
  • I tried "slds-align_absolute-center", no luck. It works for direct html "<input>" element, its just that LWC component does not allow to override css of <input> element generated by Salesforce.
    – Sriram
    Nov 16, 2019 at 19:33

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .