DEV Community

loading...

How to Create a Material Design Floating Label with ONLY Tailwind [Tailwind v2.2 Update] [2021]

Mark
Updated on ・1 min read

Originally posted on my website

In the past you'd have to write a custom plugin, reach for custom CSS or use some JavaScript to make a material floating label in Tailwind CSS.

That's all changed since Tailwind CSS v2.2 that introduced the new peer sibling selector and the placeholder-shown psuedo-class. Because of these additions you can now do this:

<div class="relative">
  <input type="text" id="name" placeholder="Name" class="peer placeholder-transparent" />
  <label for="name" class="absolute top-1/2 -translate-y-12 left-2 peer-focus:-translate-y-12 transition-transform peer-placeholder-shown:-translate-y-1/2">Name</label>
</div>
Enter fullscreen mode Exit fullscreen mode

This solution is clean, easy to read and does exactly what you want.

I'd still advise a different solution though, as placeholder-shown is not fully supported yet, as you can see on Can I Use.

Check out the Tailwind Play example

Discussion (0)