0

I have a span that shows up when Im hovering over the img. I would like now to center it in the image. How do I do that?

Like here:Pic

Here is my code:

const container = document.querySelector('#container');
const description = document.querySelector('.description');
container.addEventListener('mouseenter', e => {
  description.classList.remove('hidden');
});
container.addEventListener('mouseleave', e => {
  description.classList.add('hidden');
});
#container {
  position: relative;
  width: 100%;
}

.description {
  position: absolute;
}

.hidden {
  display: none;
}

span {
  color: #FFFFFF;
  font-size: 80px;
}
img {
  width: 50%;
}
<html lang="de">
  <body>
    <div id="container">
      <span class="description hidden">--TEXT--</span>
      <img id="image" src="https://i.pinimg.com/originals/1a/12/32/1a123232bfeaaec0a23eb0f83158e76a.jpg">
    </div>
  </body>
</html>
j08691
  • 204,283
  • 31
  • 260
  • 272
Void
  • 9
  • 3

2 Answers2

0

In order to move the text, you have to use the left and top properties. Next, you have to translate it back by half its width and height

.description {
  position: absolute:
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

Alternatively, you could use CSS Grid to position the elements which is way cleaner but check your browser support.

#container {
  position: relative;
  display: grid;
  place-items: center;
}

.description {
  position: absolute;
}
marcobiedermann
  • 4,317
  • 3
  • 24
  • 37
0

I assume that you want a covered image with a text on it. simply you can do this:

NOTE: when you give span both right:0 and left:0 it changes its width to 100%, you can give the span a color to see that

#container {
 width: 100px;
 height: 100px;
 overflow: hidden;
 position: relative;
}

#container > img {
 width: 100%;
 height: 100%;
 object-fit: cover;
}

#container > span {
 position: absolute;
 text-align: center;
 left: 0;
 right: 0;
 top: 50%;
 transform: translateY(-50%);
}
Ari Shojaei
  • 361
  • 5
  • 12