1

I can set the width of an <input type=number> field with CSS width = 6em; or width = 100%, but those only set a fixed width or a width that varies with the container. I want the width to depend on how big the number is that I've typed in.

I'm sure I can do this with JavaScript by setting width = 100% and writing the <input>'s value in the containing element (hidden somehow). But is there a way to do this without JavaScript at all? Pure CSS? I'm able to use the absolute latest bleeding-edge CSS features.

2
  • 1
    As far as I know, this is not possible without javascript Commented Jun 20, 2023 at 8:00
  • 1
    CSS doesn't really have a way to do this. There's the attr() directive, but support for that outside of the content property is basically 0. Even if you could read the value attribute of the field in this way, I don't believe that attribute updates when you modify the field. Commented Jun 20, 2023 at 8:03

1 Answer 1

0

Unfortunately, at the moment a pure CSS solution is unavailable. You can get somewhat close with a monospace font and inline event handlers like shown below. However, this doesn't work for all unicode characters.

input {
  font-family: 'Courier';
  min-width: 1ch;
  width: 1ch;
}
<input oninput="style.width = value.length+'ch'" />

The best solution currently to work with any font is to "mirror" the input text in some invisible element, measure its width, and then apply that back to the input element. However, to properly mirror the input, make sure the "mirror" element is inline, whitespace-sensitive, and matches the <input> font, like so:

input {
  font: 16px system-ui;
  min-width: 1ch;
  width: 1ch;
}

#mirror {
  font: 16px system-ui;
  display: inline;

  position: absolute;
  visibility: hidden;
  left: 0;
}
<input oninput="mirror.textContent = value; style.width = Math.ceil(mirror.offsetWidth)+'px'">
<pre id="mirror"></pre>

Sign up to request clarification or add additional context in comments.

4 Comments

The ch unit doesn't quite match up to the right width, I think the font needs to be a specific monospace font? The last solution at css-tricks.com/auto-growing-inputs-textareas has a similar answer, using dataset and attr() that does work in all browsers and has only a single line of JavaScript for theoninput attribute.
The ch unit should work with any monospace font I think; it works with 'Courier' on my machine within all browsers. What behavior are you seeing? Make sure your <input>s also have box-sizing: content-box;
I don't want a monospace font though for the number input fields.
@at. I have updated my answer to work with non-monospace fonts. It's still not pure CSS, but it's minimal JavaScript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.