Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to vertically and horizontally center text within a image?

I’m working on a React component using Tailwind CSS, and I’m trying to achieve a specific layout. I have a div with an image and two paragraphs inside it. I want the paragraphs to be centered both horizontally and vertically within the div so that they appear at the center of the image.

Here’s my current code:

<div className="flex flex-col items-center justify-center text-center">
  <img src="img/slider1.png" alt="slider1" className="mb-4" />
  <p className="font-bold">This paragraph is full of cats</p>
  <p>This paragraph is not.</p>
</div>

Output Of Code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Despite using items-center and justify-center, the text is not aligning exactly at the center of the image. I want both paragraphs to be positioned at the center, both horizontally and vertically, within the div.

Any suggestions or corrections to my current approach would be greatly appreciated. Thank you!

>Solution :

  1. Wrap your image and paragraphs
  2. Use absolute positioning for the paragraphs
  3. Center the text both horizontally and vertically.
<div className="relative">
  <img src="img/slider1.png" alt="slider1" />
  <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 text-center">
    <p className="font-bold mb-2">This paragraph is full of cats</p>
    <p>This paragraph is not.</p>
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading