Search code examples
cssreactjstailwind-css

Is there a way to add text on top of an image using tailwind?


I'm trying to place text and a button over top of an image, and then have other components and text beneath that image using tailwind. I've tried using absolute positioning, but the issue with that is the image no longer takes up vertical space, and so the "Text Beneath Image" will disappear behind the image.

I want something that looks something similar to this:

enter image description here

Is there a way to achieve this using tailwind?


Solution

  • I think you should group the components using <div>. The first component group includes images and over text and button, second component group includes "Text Beneath Image" text and button. Like following....

    <div className="relative text-center">
      <img
         src="https://hips.hearstapps.com/hmg-prod/images/ground-cover-flowers-1-6477baad1ae88.jpg?crop=1xw:0.675xh;center,top&resize=1200:*"
          alt="img"
       />
       <div className="w-full absolute top-0 left-0 text-center mt-10">
          <h2 className="text-4xl font-bold text-red-500 text-center">
             TailwindCSS + React
          </h2>
          <button className="mt-10 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
              Test Button
          </button>
        </div>
    </div>
    <div className="text-center mb-10">
        <h2 className="text-2xl font-bold">Text 2</h2>
        <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
           Test Button 2
        </button>
     </div>
    

    You can check my test project using following url. https://codesandbox.io/p/sandbox/epic-feistel-rs237k?file=%2Fsrc%2FApp.js