Tailwind CSS: Expand a Text Input on Focus (without Javascript)

Updated: December 9, 2023 By: Khue Post a comment

The example below shows you how to create an animated text field that can expand its width on focus (and shrink when losing focus). We’ll achieve this thing with only Tailwind CSS. No Javascript code is required.

Preview:

The code:

<body>
    <div class="w-screen h-screen bg-indigo-700 p-20">
        <h1 class="text-2xl text-white font-light mb-10">Animated Search Field Example</h1>
        <form>
            <input type="text" name="search" placeholder="Search slingacademy.com" class="bg-white px-5 py-3 text-gray-800 w-64 border-0 rounded-full 
            focus:outline-0 focus:w-full duration-500" />
        </form>
    </div>
</body>

Code explained:

  • In the beginning, the width of the input is set to w-64. When it gets focused, the width expands to w-full (the width of the parent). We styled the search field on the focus state by using the focus modifier.
  • To make the change smooth and not sudden, we added the duration-500 utility class.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments