DEV Community

loading...

Floating Button On Image Using Tailwind

Dendi Handian
I am that backend programmer who doesn't return 200 OK for errors and doesn't write only POST method for all endpoints.
Updated on ・2 min read

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.


Discussion (0)