Implementing Input Autocomplete Visuals

For WebShell-like command inputs, fake partial highlighting by layering a positioned div behind the input; CSS alone can’t color only the suffix.

Nov 25, 2023 · 1 min read · 162 Words · -Views -Comments · Programming
WebShell CSS JavaScript 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

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.

https://static.1991421.cn/2023/2023-11-25-173413.jpeg

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

  1. Insert a <div> before the input that displays the full completion string. Give it the desired completion color.
  2. Absolutely position the div so its text overlaps the input text exactly.
  3. 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

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover