Tailwind CSS: How to place text over an image

Updated: December 7, 2023 By: Khue Post a comment

This concise, practical article walks you through a few examples of placing text over an image by using Tailwind CSS.

What is the Point?

The key point of placing text on an image can be summed up in the following steps:

  • Put the image and text in a div element. This div element will have a position of relative
  • Set the position of the text to absolute
  • Use one or some of the utility classes top-*, left-*, bottom-*, right-* to position the text

Now let’s apply this idea in practice.

Precisely Position the Text on the Image

This example places some text in the center, center bottom, bottom right, and top left of an image.


The code:

<body class="p-10">
    <div class="relative">
        <img class="w-full" src="https://www.slingacademy.com/wp-content/uploads/2022/10/night-sky.jpeg" />
        <h1 class="absolute text-5xl text-white top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2">
            Sling Academy</h1>
        <h2 class="absolute text-3xl text-amber-400 bottom-4 left-1/2 -translate-x-1/2">Bottom Center</h2>
        <h3 class="absolute text-2xl text-blue-300 top-5 left-5">Top Left</h3>
        <h3 class="absolute text-2xl text-green-300 bottom-5 right-5">Bottom Right</h3>

Put Text Over an Image and Add a Contrasting Background

In many cases, images are loaded from the server dynamically. Therefore, we do not know whether the color scheme of the image is light or dark. To make sure the text is always clear and easy to read, we’ll add a high-contrast background color with a certain amount of transparency around it.


The code:

<body class="p-10">
    <div class="relative w-[500px]">
        <img src="https://www.slingacademy.com/wp-content/uploads/2022/10/cute-dog.jpeg" />
        <div class="absolute bottom-0 left-0 right-0 px-4 py-2 bg-gray-800 opacity-70">
            <h3 class="text-xl text-white font-bold">
                Hey, I Am The Big Boss</h3>
            <p class="mt-2 text-sm text-gray-300">Some description text. Some dummy text here. Welcome to Sling Academy.

That’s it. Happy coding & have a nice day with Tailwind CSS.