Explain Codes LogoExplain Codes Logo

Html text input field with currency symbol

html
responsive-design
best-practices
accessibility
Nikita BarsukovbyNikita Barsukov·Feb 23, 2025
TLDR

Embed a currency symbol directly inside an HTML input field using a CSS trick that employs relative positioning. The trick involves placing a <span> tag displaying a currency symbol next to an input field:

<div style="display: inline-block; position: relative;"> <span style="position: absolute; left: 5px; top: 50%; transform: translateY(-50%);">$</span> <input type="text" style="padding-left: 20px;" /> </div>

Creating the illusion of a single element, this snippet produces a neatly integrated $ symbol. To adapt it to your layout, tweak the padding and span positioning.

Your CSS arsenal for better UX

Deploying pseudo-elements

By using a CSS ::before pseudo-element, you can create a permanent "$" prefix in the input field.

.input-with-symbol::before { content: '$'; position: absolute; margin-left: 5px; pointer-events: none; /* Just waving the magic wand of W3C here 😉 */ }

Dressing up your input field

To make the typing point clear for users, style the input using CSS:

.input-with-symbol input[type="text"] { border: 1px solid #ccc; padding-left: 25px; /* Preparing a royal seat for our $-gentleman 💺 */ /* Lay down the red carpet for more styling here */ }

Upscaling accessibility and readability of input

Keep accessibility in mind for all users:

  • Use label elements for assistive technologies.
  • Continue with validation highlighting to show field status.
  • Align the text right with text-align: right;, if fitting your locale numeric format.

Craft deployment with inline SVG

For the currency symbol, you could use a background SVG rather than a text:

.input-with-symbol input[type="text"] { background-image: url("data:image/svg+xml,..."); background-repeat: no-repeat; background-size: 10px 10px; background-position: left center; padding-left: 25px; /* Please keep Vincoonect the kind SVG */ }

Advanced techniques

Blackjack with JavaScript

Use JavaScript to put in dynamic formatting. It will inject commas and decimals as the user types, just like a dedicated croupier at a prestigious Blackjack table:

document.querySelector('input[type="text"]').addEventListener('input', (event) => { event.target.value = formatCurrency(event.target.value); /* This here is a service as swift as DHL 🚚 */ });

Test, test, repeat

Ensure to:

  • Check browser support for the CSS techniques you've employed, especially when using background SVGs.
  • Test the input field across a range of browsers and devices to guarantee uniform performance.

Embrace global currency localization

When catering to an international audience, allow flexibility with currency symbol formatting and positioning. Some regions might use a different symbol placement style.