Sling Academy
Home/Tailwind CSS/Tailwind CSS: Expand a Text Input on Focus (without Javascript)

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

Last updated: December 09, 2023

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.

Next Article: Tailwind CSS: How to Disable Resizing of Textarea

Previous Article: Tailwind CSS: How to Create a Stepper

Series: Styling Form Elements with Tailwind CSS

Tailwind CSS

Related Articles