0
<!DOCTYPE html>
<html>
    <head>
      <title>Overlay text over img</title>
      <style>
          p{
              position:absolute;
              top: 80px;
              left: 80px;
              color: white;
          }
      </style>
    </head>
    <body>
        <img src="../images/finnish.jpeg" alt="Clean">
        <p>Clean</p>
    </body>
</html>

My question is why people place img and text inside a div in html and then in css they set the position of img into relative and position of the text (in this case is p) into absolute. I tried the code above, and it still works without setting the position of img into relative. May someone explain it for me why people doing that?

Quang nGUYEN
  • 59
  • 1
  • 8

1 Answers1

0

when you set position: absolute the element's position is set based on first element with position's relative it finds. So if you don't set it, it may breakup.

BeHappy
  • 3,705
  • 5
  • 18
  • 59
  • Can you explain it's in detail, please? Because I don't know what do you mean by saying, "it may break up." Furthermore, do I have to put the img and text are in the same div? I saw people did it regularly when they want to overlay text over img, but I don't know what the point for doing it is? – Quang nGUYEN Apr 07 '20 at 22:52
  • when I want to do something like this, I put them in a `div` and set `position: relative` to `div` and `position: absolute` to text.So text is positioned based on `div` and when `div` size changed, the text will be at same position as it was, – BeHappy Apr 08 '20 at 14:24
  • Tks a lot. It is very helpful – Quang nGUYEN Apr 09 '20 at 03:10