Add a text suffix to <input type=“number”>

前端 未结 4 819
盖世英雄少女心
盖世英雄少女心 2020-12-06 00:07

I currently have a number of inputs like this:


This input field is used to represent a va

4条回答
  •  余生分开走
    2020-12-06 01:01

    You can use a wrapper

    for each input element and position the unit as a pseudo element ::after with the content of your corresponding units.

    This approach works well for the absolute positioned pseudo elements will not effect the existing layouts. Nevertheless, the downside of this approach is, that you have to make sure, that the user input is not as long as the text field, otherwise the unit will be unpleasantly shown above. For a fixed user input length, it should work fine.

    /* prepare wrapper element */
    div {
      display: inline-block;
      position: relative;
    }
    
    /* position the unit to the right of the wrapper */
    div::after {
      position: absolute;
      top: 2px;
      right: .5em;
      transition: all .05s ease-in-out;
    }
    
    /* move unit more to the left on hover or focus within
       for arrow buttons will appear to the right of number inputs */
    div:hover::after,
    div:focus-within::after {
      right: 1.5em;
    }
    
    /* handle Firefox (arrows always shown) */
    @supports (-moz-appearance:none) {
      div::after {
        right: 1.5em;
      }
    }
    
    /* set the unit abbreviation for each unit class */
    .ms::after {
      content: 'ms';
    }
    .db::after {
      content: 'db';
    }
    .percent::after {
      content: '%';
    }


    If you want to support browsers, that doesn't show these arrows at all, make use of @supports or media queries.

提交回复
热议问题