skip to Main Content

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

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!

2

Answers


  1. You can change your code like this. Use an div to wrap it.

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

    Add h-screento the outer div to ensure that it takes the full height of the viewport.

    Also use an additonal div to center the paragraphs both horizontally and vertically.

    Login or Signup to reply.
    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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search