Niels Peeren Niels Peeren - 2 months ago 20
CSS Question

Keep text on foreground with scale effect on image

I have an image gallery with a hover effect. once the user hovers over the image it uses a css transform.

transform: scale(1.1);


The image looks like this without the hover effect.
enter image description here

and with the effect it looks like this.
enter image description here

As you can see it does zoom in nicely but somehow the text disapears in the background. I tried using z-index but this has no effect. How do I keep the text in the front?
Here is a jsfiddle : https://jsfiddle.net/xk2us9q8/

Answer

z-index requires a positioning value other than static to take effect.

Just add position:relative to the text.

.container {
  width: 350px;
  height: 350px;
  padding: 0px;
  margin: 0px;
  overflow: hidden;
}
p {
  color: white;
  width: 350px;
  text-align: center;
  font-size: 28px;
  z-index: 100;
  margin-top: -90px;
  position: relative;
}
.dnnmedia_image {
  width: 350px;
  height: 350px;
  transition: all .2s ease-in-out;
  overflow: hidden;
  object-fit: cover;
}
.dnnmedia_image:hover {
  transform: scale(1.1);
}
<div class="container">
  <img src="https://dummyimage.com/350x350/000/fff" class="dnnmedia_image" />
</div>
<p>
  Random text
</p>

Comments