1

I'm using an image and trying to position some text in front of the image and center, as seen in the screenshot from my design below:

enter image description here

I'm using the below code and found out how to layer the text over the top with z-index, but I'm wondering how I can center the text inside the parent div as seen in the design?

Code:

<div style={{ display: `flex`, flexDirection: `column` }}>
    {/* image and title */}
    <div>
      <StaticImage
        src="../images/home.png"
        width={1000}
        quality={100}
        formats={["auto", "webp", "avif"]}
        alt="home image"
        style={{ marginBottom: `1rem`, zIndex: `1` }}
      />
      <div style={{
            position: `absolute`,
            top: `50%`,
            left: `50%`,
            transform: `translate(-50%, -50%)`,
            zIndex: `2`,
            display: `flex`,
            justifyContent: `spaceBetween`,
            flexDirection: `row`
          }}>
        <h1 style={{
            color: `white`,
            fontSize: `7vw`
          }}>Gareth</h1>
        <h1 style={{
            color: `white`,
            fontSize: `7vw`
          }}>Veale</h1>
        </div>
    </div>
</div>

However, this gives me the text centered on the entire page i think? Perhaps due to the 50% top/left properties?

enter image description here

1 Answer 1

2

you should set a width to the parent div to see the difference in flex alignment.

See the code below.

<div style={{ display: `flex`, flexDirection: `column` }}>
{/* image and title */}
<div>
  <StaticImage
    src="../images/home.png"
    width={1000}
    quality={100}
    formats={["auto", "webp", "avif"]}
    alt="home image"
    style={{ marginBottom: `1rem`, zIndex: `1` }}
  />
  <div style={{
        position: `absolute`,
        top: `50%`,
        left: `10%`,
        width: `80%`,
        transform: `translate(-50%, -50%)`,
        zIndex: `2`,
        display: `flex`,
        justifyContent: `spaceBetween`,
        flexDirection: `row`
      }}>
    <h1 style={{
        color: `white`,
        fontSize: `7vw`
      }}>Gareth</h1>
    <h1 style={{
        color: `white`,
        fontSize: `7vw`
      }}>Veale</h1>
    </div>
</div>

As you can see i just changed the left and width parameters to get the expected result. I hope this will solve your problem

Sign up to request clarification or add additional context in comments.

1 Comment

If my answer was correct please consider setting it as Correct answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.