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

Updated: June 16, 2022 By: Pennywise 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 by KindaCode.com</h1>
        <form>
            <input type="text" name="search" placeholder="Search" class="bg-white px-5 py-3 text-gray-800 w-48 border-0 rounded-full 
            focus:outline-0 focus:w-full duration-500" />
        </form>
    </div>
</body>

Explanations

  • In the beginning, the width of the input is set to w-48 (12rem or 192px). 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.

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

Related Articles