JanisOzolins JanisOzolins - 4 months ago 10
CSS Question

How to vertically center on hover element text?

I have a text element that appears over the image on mouseover. The text bit is horizontally centered but I'm still having troubles centering it vertically despite trying several techniques. Trying to achieve this without Javascript.

HTML:

<figure class="wp-caption-my">
<img class="demo-my" src="image.png" alt="Image" />
<figcaption class="wp-caption-text-my">This is a caption text</figcaption>
</figure>


CSS:

.wp-caption-my {
position: relative;
padding: 0;
margin: 0;
}

.wp-caption-my img {
display: block;
max-width: 100%;
height: auto;
}

.wp-caption-text-my {
opacity: 0;
position: absolute;
width: 100%;
height: 100%;
color: #fff;
left: 0;
bottom: 0;
padding: 0.75em 1em;
font-weight: 700;
z-index: 2;
-webkit-box-sizing: border-box;
box-sizing: border-box;
background-color: rgba(0,191,255,0.9);
text-align: center;
-webkit-transition: opacity .3s ease-in-out !important;
transition: opacity .3s ease-in-out !important;
}

.wp-caption-my:hover .wp-caption-text-my {
opacity: 1;
}

img.demo-my {
width: 100% !important;
height: 100% !important;
}

Answer

I think you can use CSS pseudo elements this way:

.wp-caption-my {
position: relative;
padding: 0;
margin: 0;
}

.wp-caption-my img {
display: block;
max-width: 100%;
height: auto;
}

.wp-caption-text-my {
opacity: 0;
position: absolute;
width: 100%;
height: 100%;
color: #fff;
left: 0;
bottom: 0;
padding: 0.75em 1em;
font-weight: 700;
z-index: 2;
-webkit-box-sizing: border-box;
box-sizing: border-box;
background-color: rgba(0,191,255,0.9);
text-align: center;
-webkit-transition: opacity .3s ease-in-out !important;
transition: opacity .3s ease-in-out !important;
}

.wp-caption-my:hover .wp-caption-text-my {
opacity: 1;
}

.wp-caption-text-my::before {
content: "";
  display: inline-block;
  width: 0px;
  height: 100%;
  vertical-align: middle;
}

.wp-caption-text-my span {
display: inline-block;
  vertical-align: middle;
}

img.demo-my {
width: 100% !important;
height: 100% !important;
}
<figure class="wp-caption-my">
    <img class="demo-my" src="http://janisweb.tk/grahams/wp-content/uploads/2016/07/officewaste.png" alt="Image" />
    <figcaption class="wp-caption-text-my"><span>This is a caption text</span></figcaption>
</figure>

This is done by wrapping your text in a span and adding this CSS to your styles:

.wp-caption-text-my::before {
  content: "";
  display: inline-block;
  width: 0px;
  height: 100%;
  vertical-align: middle;
}

.wp-caption-text-my span {
  display: inline-block;
  vertical-align: middle;
}