Search code examples
htmlcssposition

Text over an image in HTML not positioning correctly


I made my text over my image correctly, but the problem is I can't figure out how to make the text in its fixed place without moving when resizing the window.
Here is my code:

img {
  height: 100%;
  width: 100%;
  box-shadow: 0 0 10px black;
}

h1 {
  font-family: 'Courier', monospace;
  font-size: 1rem;
}

.container {
  height: 100vh;
  width: 50vh;
  position: relative;
  text-align: center;
}

.firstName {
  position: absolute;
  top: 0;
  left: 3em;
}

.secName {
  position: absolute;
  top: 1em;
  left: 5em;
  color: rgb(200,0,0);
}
<div class="container">
  <img src="https://i.pinimg.com/564x/ee/84/e5/ee84e597b90f4b6d827f4c73506e700d.jpg">
  <div class="firstName">
    <h1>Eren</h1>
  </div>
  
  <div class="secName">
    <h1>Yeager</h1>
  </div>
  
</div>

You see, when you resize the window the text pop out from the image box.


Solution

  • To make your text linked to the specified position on the image you may set text positioning in percentage. Here is the way that can solve it:

    img {
      height: 100%;
      width: 100%;
      box-shadow: 0 0 10px black;
    }
    
    h1 {
      font-family: 'Courier', monospace;
      font-size: 1rem;
    }
    
    .container {
      height: 100vh;
      width: 50vh;
      position: relative;
      text-align: center;
    }
    
    .firstName {
      position: absolute;
      top: 0;
      left: 40%;
      transform: translateX(-50%);
    }
    
    .secName {
      position: absolute;
      top: 1em;
      left: 60%;
      transform: translateX(-50%);
      color: rgb(200,0,0);
    }
    <div class="container">
      <img src="https://i.pinimg.com/564x/ee/84/e5/ee84e597b90f4b6d827f4c73506e700d.jpg">
      <div class="firstName">
        <h1>Eren</h1>
      </div>
      
      <div class="secName">
        <h1>Yeager</h1>
      </div>
      
    </div>