Text over an image is very common in modern website design. Images having text on the top looks nice and also engage users on the web page. You can add text on an image in TailwindCSS by using the following 2 simple methods.
Method 1: Using Background Image to Add Text over Image in TailwindCSS
The first and simple method is to use a background image in TailwindCSS and then add text over it. For this method, you also need to use CSS positioning to achieve what you are looking for. In this method, you have to set a background image and give relative
the position to it and then you can add text with position absolute
and the text will be on the top of the image. You can check the following code to see how it will work.
1 2 3 4 5 6 7 8 9 10 11 12 |
<div class="bg-[url(https://placekitten.com/600)] h-[600px] w-[600px] relative"> <div class="absolute bottom-0 px-4 py-3 bg-gray-500/50 w-full"> <h1 class="text-white font-semibold text-4xl"> Kittens are cute </h1> <p class="text-gray-200"> I love kittens very much. They are amazing. </p> </div> </div> |
Here is the working code example on the tailwind playground and the output is shown below in the screenshot.
Method 2: Using Positioning in TailwindCSS to Place Text on an Image
If you don’t want to use the background image to place text on an image, the second method is for you. In this method, you don’t have to use the image as background but you surely need position classes. The following example uses an image and the text is placed on the image with absolute
position.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<div class="h-[600px] w-[600px] relative"> <img src="https://placekitten.com/600" alt=""> <div class="absolute bottom-0 px-4 py-3 bg-gray-500/50 w-full"> <h1 class="text-white font-semibold text-4xl"> Kittens are cute </h1> <p class="text-gray-200"> I love kittens very much. They are amazing. </p> </div> </div> |
You can check the working code example and the output will remain the same as the first method.
Conclusion
There are 2 simple methods to place text on an image using TailwindCSS. In the first method, you can use the image as a background image and place text on it. In the second method, you can add text directly to an image without using it as a background image. Please note that in both these methods, you have to use the position relative
on the parent container and absolute
on the child. You might want to check our other posts about making a background image blur in TailwindCSS or adding an overlay on the background image in TailwindCSS.