Implementing Input Autocomplete Visuals
·
1 min read
·
162
Words
·
-Views
-Comments
While building a WebShell UI I needed an input box that shows autocomplete suggestions inline. The logic was straightforward, but the visual treatment required a small trick.
In the screenshot, typing h
reveals ello
as the completion. The suffix must appear in a different color.
Browsers don’t let you color arbitrary substrings inside an <input>
with pure CSS. That means we need a DOM + JavaScript workaround.
Approach
- Insert a
<div>
before the input that displays the full completion string. Give it the desired completion color. - Absolutely position the div so its text overlaps the input text exactly.
- Keep the input on top using stacking context so the user can still place the caret and type normally.
Notes
- The higher z-index on the input prevents the completion layer from intercepting the cursor or mouse selection.
- The completion div should contain the full string (e.g.,
hello
). Match the font size, weight, letter-spacing, etc., so the overlay aligns perfectly with the input.
Demo
https://github.com/alanhe421/express-demo/blob/master/test/input-completion/index.html