Search code examples
htmlcsscss-positionvertical-alignmentcentering

Center text vertically and horizontally over image when resized


I'm trying to center text over an image; however, whenever I resize it, the text does not stay vertically centered.

.hero-image {
  margin: 0 auto;
}

.hero-image img {
  width: 100%;
}

.hero-text {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}
<div class="hero-image">
  <img src="https://content.codecademy.com/courses/freelance-1/unit-4/img-mission-background.jpg">
  <div class="hero-text">
    Here is the hero text
  </div>
</div>

Here's what's happening: Working properly: enter image description here

Vertical centering is off when resizing: enter image description here


Solution

  • Your css for your hero text looks good – If I'm understanding your question correctly, I think the image should be modified to use 100 viewport width / height rather than 100%.

    body {
      margin: 0;
    }
    
    .hero-image img {
      width: 100vw;
      height: 100vh;
      object-fit: cover;
    }
    
    .hero-text {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      text-align: center;
    }
    enter image description here

    enter image description here

    enter image description here