How to Create an Autocomplete using CSS?

Autocomplete is a feature that suggests possible completions for an input field as the user types, typically seen in search boxes. It enhances user experience by providing real-time suggestions and helping users find what they’re looking for faster and more efficiently.

Approach

  • Create the basic webpage structure using HTML, including input field and list elements for autocomplete.
  • Apply CSS styles to enhance the visual appearance of the page, including the navbar, input field, and autocomplete dropdown.
  • Integrate JavaScript to handle autocomplete functionality, listening for user input.
  • Implement logic to filter and display autocomplete suggestions based on user input.
  • Manage user interactions, such as selecting suggestions and updating the input field accordingly.

Example: The example below shows how to create an Autocomplete using CSS.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <style>
        * {
            box-sizing: border-box;
        }

        body {
            font-family: Arial, sans-serif;
            background-color: #f9f9f9;
        }

        .navbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #2e2e2e;
            padding: 10px 20px;
            color: #fff;
        }

        .navbar img {
            max-width: 200px;
            display: block;
            margin: 0 auto;
        }

        .auto {
            position: relative;
            display: inline-block;
            width: 300px;
            margin: 20px;
        }

        input[type="text"] {
            width: 100%;
            padding: 10px;
            font-size: 16px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: #fff;
            transition: border-color 0.3s ease;
        }

        input[type="text"]:focus {
            border-color: DodgerBlue;
        }

        ul {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            z-index: 99;
            border: 1px solid #ddd;
            border-top: none;
            border-radius: 0 0 4px 4px;
            background-color: #fff;
            list-style-type: none;
            padding: 0;
            margin: 0;
        }

        li {
            padding: 10px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        li:hover {
            background-color: #f4f4f4;
        }
    </style>
</head>

<body>

    <nav class="navbar">
        <img src=
"https://media.w3wiki.net/gfg-gg-logo.svg" alt="Logo">
    </nav>

    <h2>Autocomplete Example</h2>
    <p>Type to search for a fruit:</p>

    <form autocomplete="off">
        <div class="auto">
            <input id="frInput" type="text" 
                   name="fruit" placeholder="Fruit">
            <ul id="frList" class="lst"></ul>
        </div>
    </form>

    <script>
        const frts = ["Apple", "Apricot", "Avocado", 
                      "Banana", "Blackberry", "Blueberry", 
                      "Cherry", "Coconut", "Cranberry", 
                      "Date", "Dragonfruit", "Durian", 
                      "Fig", "Grape", "Grapefruit", 
                      "Guava", "Kiwi", "Lemon", "Lime", 
                      "Lychee", "Mango", "Melon", "Nectarine", 
                      "Orange", "Papaya", "Peach", "Pear", 
                      "Pineapple", "Plum", "Pomegranate", 
                      "Raspberry", "Strawberry", 
                      "Watermelon"];

        let srtNames = frts.sort();
        let ipt = document.getElementById("frInput");
        let lst = document.getElementById("frList");

        ipt.addEventListener("keyup", (e) => {
            rmvElements();
            for (let i of srtNames) {
                if (i.toLowerCase()
                     .startsWith(ipt.value.toLowerCase()) 
                                    && ipt.value != "") {
                    let lstItem = document.createElement("li");
                    lstItem.classList.add("lst-items");
                    lstItem.style.cursor = "pointer";
                    lstItem.setAttribute("onclick", 
                                         "dspNames('" + i + "')");
                    let word = "<b>" 
                        + i.substr(0, ipt.value.length) + "</b>";
                    word += i.substr(ipt.value.length);
                    lstItem.innerHTML = word;
                    lst.appendChild(lstItem);
                }
            }
        });

        function dspNames(value) {
            ipt.value = value;
            rmvElements();
        }

        function rmvElements() {
            let items = document.querySelectorAll(".lst-items");
            items.forEach((item) => {
                item.remove();
            });
        }
    </script>

</body>

</html>

Output:



Contact Us