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:
- Tailwind CSS: How to Disable Text Selection
- Form Validation with Tailwind CSS (without Javascript)
- Using Tailwind CSS with Font Awesome Icons: A Deep Dive
- Full-Screen Search Box with Tailwind CSS
- How to Style a Pagination with Tailwind CSS
- Tailwind CSS: Create an Animated & Closable Side Menu
You can also check out our CSS category page for the latest tutorials and examples.