Volper
Volper

Reputation: 684

How to add a unit to the end of <input type="number"> properly in HTML(5)?

I would like to have an <input type="number"> that has a unit at the end (m2), but the user can't change it. I have this for now:

<label>
  Area:
  <input type="number" name="area">
</label>

I guess I can't just add a unit directly after the <input> because that would probably mess up the <label>. So what do I do? Would it be best to separate the <label> using the for attribute or add an ::after pseudo-element using CSS or what?

Upvotes: 4

Views: 9751

Answers (1)

gavgrif
gavgrif

Reputation: 15499

Although you could use the ::after pseudoselector, the best approach is to use the m2 in the label to give more contextual information to the value that is expected int the input. In other words - the label informs the user as to what the value means in the input.

Note the <sup> element that allows the superscript rendering of the 2.

<label>
  Area (m<sup>2</sup>):
  <input type="number" name="area">
</label>

You could also create a span with the content and include it within the label -after the input and it would show at the end of the input.

<label>
  Area:
  <input type="number" name="area">
  <span> m<sup>2</sup></span>
</label>

You could even position it absolutely so it shows in the input field itself - but given that this is a number type of input - browsers will insert a 'stepper at the extreme right of the field - so you would need to wither move it to the left to avoid that, or use a type="text" input and validate the input to be numeric.

label {
  position: relative;
}

label span {
  position: absolute;
  top: -1px;
  right: 24px;
}
<label>
  Area:
  <input type="number" name="area">
  <span> m<sup>2</sup></span>
</label>

Upvotes: 6

Related Questions