Home  >  Article  >  Web Front-end  >  How can I add custom text suffixes to number inputs using CSS for better user comprehension?

How can I add custom text suffixes to number inputs using CSS for better user comprehension?

Linda Hamilton
Linda HamiltonOriginal
2024-10-27 10:29:30581browse

How can I add custom text suffixes to number inputs using CSS for better user comprehension?

Enhance Number Inputs with Custom Text Suffixes

You have multiple number inputs representing values in milliseconds, dB, and percentages. To enhance user comprehension, you want to add type suffixes to these inputs, indicating the unit of measurement.

Solution Using CSS Wrapper and Pseudo Element

Instead of modifying the input elements themselves, you can use a CSS wrapper and a pseudo element to achieve the desired result:

  1. Create a wrapper div for each input:

    • This div will position the text suffix and ensure it doesn't disrupt the layout.
  2. Position the suffix as a pseudo element (::after):

    • Set its position to absolute, allowing it to float outside the wrapper div.
    • Place it at the specified offset (e.g., right: 0.5em) to align with the input.
  3. Adjust the position on hover or focus:

    • On hover or focus within the wrapper, move the suffix slightly further away (e.g., right: 1.5em). This accommodates arrow buttons in some browsers.
  4. Provide custom suffixes:

    • Use separate CSS classes for each unit (e.g., .ms, .db, .percent).
    • Set the content property of the pseudo element within each class to display the desired suffix (e.g., 'ms', 'db', '%').

Example Code:

<code class="css">div {
  display: inline-block;
  position: relative;
}
div::after {
  position: absolute;
  top: 2px;
  right: .5em;
  transition: all .05s ease-in-out;
}
div:hover::after,
div:focus-within::after {
  right: 1.5em;
}
@supports (-moz-appearance:none) {
  div::after {
    right: 1.5em;
  }
}
.ms::after {
  content: 'ms';
}
.db::after {
  content: 'db';
}
.percent::after {
  content: '%';
}</code>
<code class="html"><div class="ms">
  <input type="number" id="milliseconds" />
</div>
<hr />
<div class="db">
  <input type="number" id="decibel" />
</div>
<hr />
<div class="percent">
  <input type="number" id="percentages" />
</div></code>

Now, your number inputs will display the type suffixes, enhancing clarity and user understanding.

The above is the detailed content of How can I add custom text suffixes to number inputs using CSS for better user comprehension?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn