Full-Screen Search Box with Tailwind CSS

Last updated on June 14, 2022 Pennywise Loading... Post a comment

The example below shows you how to create a full-screen search box with Tailwind CSS and a few lines of vanilla Javascript (it’s totally fine if you don’t have much experience with this programming language).

Example preview:

The code:

<body class="p-20 bg-amber-100">
    <h2 class="text-3xl">KindaCode.com</h2>
    <h3 class="text-xl my-5">Full-Screen Search Example</h3>
    <button class="px-5 py-2 bg-blue-500 hover:bg-blue-700 text-white rounded-full" onclick="openSearchBox()">
        Open Search Box</button>

    <div id="search-box" class="hidden fixed top-0 left-0 w-screen h-screen bg-gray-900 z-90">
        <span class="cursor-pointer text-6xl text-white hover:text-amber-500 absolute right-5 top-5" onclick="closeSearchBox()" title="Close">&times;</span>
        <div class="w-full h-full flex justify-center items-center">
            <form action="">
                <input type="text" placeholder="What are you looking for?" name="search"
                    class="w-96 px-3 py-2 rounded-tl-full rounded-bl-full border-0 focus:outline-0">
                <button type="submit" class="px-3 py-2 -ml-1.5 bg-green-500 hover:bg-green-600 text-white rounded-tr-full rounded-br-full">Search</button>
            </form>
        </div>
    </div>

    <!-- Javascript code -->
    <script>
        var searchBox = document.getElementById("search-box");

        function openSearchBox() {
            searchBox.classList.remove("hidden");
        }

        function closeSearchBox() {
            searchBox.classList.add("hidden");
        }
    </script>
</body>

Code explained

  • Our search box is initially hidden (with the hidden utility).
  • The openSearchBox() function is used to open the search box.
  • Our full-screen search box has a dark gray background color, a fixed position (with the fixed utility), and z-index of 90 (with the z-90 utility).
  • We center the search form by adding the flex, justify-center, and items-center classes to the parent <div>.
  • The closeSearchBox() function is used to close the search box.

Further reading:

You can also check out our CSS category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like