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">
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>
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>
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>
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>
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>
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>
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.
Top comments (1)
and how to center horizontally and vertically? Right in the middle of the image?