Html input auto-width work-around

This is a workspace post. It's a working document of my thoughts as I built something or pieced together an idea. It might be unstructured and contain spelling errors. It also might not look good on a small screen. But it could be useful to someone or related to another post, so I'm publishing it as-is.

This is a little hello-world-ish, but here goes. There's a weird part of using flexbox where a child element will fill the parent's available space only if the child has content. There's only ever and issue when the child element is an input, because the input element's interior value isn't taken into account when calculating width.

It's something that's been brought up on Stack Overflow a couple of times.[0][1] But there doesn't seem to be a solid answer, so here's a crude work-around.

Here's an example of what we want. There are three elements; a directory, a slash, and a file. The first and last will grow to fill space. Renders okay since they're all just divs.

directory
/
untitled.txt
very_long_directory_that_goes_on_for_a_while
/
untitled.txt

Here's the same example, but with an editable input. Notice that the input just stays that width. It's either fixed width, or, at best, we could expand it to 100% of parent.

/
untitled.txt
/
untitled.txt

You end up with an input that doesn't respect it's min-width, or max-width (55px and 188px respectively) because it defaults to the user agent stylesheet.

Here's how we fix it. We create a second element below the input that mirrors its exact styling, and set the input width to be 100% of container. The mirror element is the one that uses min and max widths, so it'll grow as wide as it needs to up to the limit. We then turn off overflow on the element that holds the two, and link them with a little JS, so they have the same content.

The result is an input that grows as wide as its parent, and the parent grows as wide as the widest child, and that the widest child has the same content as the input. Ta da!

try editing me
/
untitled.txt

It's unfortunate that we need JS for this, but since you're using an input anyway, odds are you're building something interactive.


workspace | css | html
2021-11-28