Home > Back-end >  Center text vertically and horizontally over image when resized
Center text vertically and horizontally over image when resized

Time:01-15

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 >
  <img src="https://content.codecademy.com/courses/freelance-1/unit-4/img-mission-background.jpg">
  <div >
    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

CodePudding user response:

You need to set the boundary of the container for positioned child. Add position: relative to .hero-image class. Otherwise it's using the next relative parent for it.

.hero-image {
  margin: 0 auto;
  position: relative;
}

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

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

CodePudding user response:

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

CodePudding user response:

You can try this translate-free solution:

.hero-text {
    position: absolute;
    top: 33vw;
    text-align: center;
    width: 100%;
}

If you plan to keep the image stretched over the whole width.

CodePudding user response:

You can do it with "display: flex".

.hero-image {
    background-image: url(https://content.codecademy.com/courses/freelance-1/unit-4/img-mission-background.jpg);
    background-size: cover;
    background-position: center;
    width: 100%;
    height: 100vh;
    display: flex;
  justify-content: center;
  align-items: center;
  }
  
  .hero-image img {
    width: 100%;
  }
  
  .hero-text {
  }
  •  Tags:  
  • Related