Explain Codes LogoExplain Codes Logo

How to align texts inside of an input?

html
text-alignment
css-classes
ux-design
Nikita BarsukovbyNikita Barsukov·Aug 6, 2024
TLDR

The right wand incantation to align text in an input is applying text-align: center; in your CSS for centering. Here's how:

input.centered { text-align: center; /* Targets center alignment, like an arrow! */ }

The CSS spell must be recited with the proper HTML element:

<input type="text" class="centered" placeholder="Aligned Text"/>

Bingo! The text you type and the placeholder within the input are now centered. For left or right alignment, simply replace center with left or right.

To bring the text to the right (no political implications), here you go:

input.right-aligned { text-align: right; /* Hipsters text aligning right */ }

And the relevant HTML:

<input type="text" class="right-aligned" placeholder="Right Aligned"/>

Steps to align text for various input types

When dealing with different input types, consider the essence of the content. For numeric inputs, it's more common to right-align.

input[type=number] { text-align: right; /* Numbers lean to the right */ }

For path or URLs, two properties, namely direction: rtl; and text-align: left;, will anchor the start of the path to the right, making it visible all the time. It's a UX trophy!

input[type=text].path { direction: rtl; text-align: left; }

And let's handle the text overflow properly in inputs using text-overflow: ellipsis;. Runaway text, beware!

Embrace classes and frameworks.

Using Bootstrap? .text-right class is your handy tool. Not using any frameworks? Creating a custom class like .text-center or .text-right turns your code into a neat poetry.

Narrowing down to specifics: Special cases and challenges

Let's start basic: Text directionality

In languages written from right-to-left like Arabic, Hebrew, etc., use direction: rtl;.

input[type=text].rtl { direction: rtl; /* Respecting RTL writers */ }

Dealing with Numeric Inputs

For numeric fields, sticking to right-alignment is a good idea:

input[type=number] { text-align: right; /* Because numbers like the right side */ }

Overflow traumas? No more!

text-overflow: ellipsis; to the rescue when long text inputs seem to flow out and mess up:

input.long-text { text-overflow: ellipsis; /* No more running away, long text! */ }

Sparkling Clean Code: Custom Classes

Create simple, reusable classes, and say goodbye to inline styling:

.text-center {/* Born to align text to the center */} .text-right {/* Loves bringing text to the right */}

Apply these classes to your inputs as required. It's that simple!