Floating Button On Image Using Tailwind

dendihandian

Dendi Handian

Posted on June 15, 2021

Floating Button On Image Using Tailwind

You can follow and code along at https://play.tailwindcss.com/

Base Image Element

Let'say we have this image on the page:

<img src="https://dummyimage.com/500x250" alt="dummy-image">
Enter fullscreen mode Exit fullscreen mode

To add any element overlapping on the image, we need to wrap the image inside div element that has relative position:

<div class="relative">
  <img src="https://dummyimage.com/500x250" alt="dummy-image">
</div>
Enter fullscreen mode Exit fullscreen mode

We also need to make the image fully close the wrapper using full width:

<div class="relative">
  <img class="w-full" src="https://dummyimage.com/500x250" alt="dummy-image">
</div>
Enter fullscreen mode Exit fullscreen mode

Button on the Top-Left Image

With the above code, we could already add anything like button on the image with absolute position:

<div class="relative">
  <img class="w-full" src="https://dummyimage.com/500x250" alt="dummy-image">
  <button class="absolute">Button</button>
</div>
Enter fullscreen mode Exit fullscreen mode

But to make it overlapping with the image, we need to move the absolute button to the top using top-0:

<div class="relative">
  <img class="w-full" src="https://dummyimage.com/500x250" alt="dummy-image">
  <button class="absolute top-0">Button</button>
</div>
Enter fullscreen mode Exit fullscreen mode

And there you go, now the button will stick to the top-left corner. Let's styling the button to make it looks fancy:

<div class="relative">
  <img class="w-full" src="https://dummyimage.com/500x250" alt="dummy-image">
  <button class="absolute top-0 bg-blue-500 text-white p-2 rounded hover:bg-blue-800">Button</button>
</div>
Enter fullscreen mode Exit fullscreen mode

And to make the button a little bit off from the edge, we simply add margin:

<div class="relative">
  <img class="w-full" src="https://dummyimage.com/500x250" alt="dummy-image">
  <button class="absolute top-0 bg-blue-500 text-white p-2 rounded hover:bg-blue-800 m-2">Button</button>
</div>
Enter fullscreen mode Exit fullscreen mode

How to Bottom-Left the Button?

We could easily change the top-0 class to bottom-0 on the button element.

How to Top-Right the Button?

We use top-0 and right-0 to the button element.

How to Bottom-Right the Button?

We use bottom-0 and right-0 to the button element.


💖 💪 🙅 🚩
dendihandian
Dendi Handian

Posted on June 15, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related