Is it possible to vertically center a caption on hover using the following code? I know I could add a div surrounding the figcaption tag to do an overlay, but I'd like to know if it's possible to do the same without adding more HTML code.
HTML:
<figure class="caption">
<img src="image.jpg" alt="" />
<figcaption class="caption-text">Some text</figcaption>
</figure>
CSS:
.caption {
position: relative;
}
.caption img {
display: block;
margin: 0;
}
.caption-text {
display: none;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
color: #fff;
text-align: center;
}
.caption:hover .caption-text {
display: block;
background: rgba(30, 30, 30, 0.7);
}
Thanks in advance
You can use Flexbox on .caption-text
.caption {
position: relative;
display: inline-block;
}
.caption img {
display: block;
margin: 0;
}
.caption-text {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
color: #fff;
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
transition: all 0.3s ease-in;
}
.caption:hover .caption-text {
background: rgba(30, 30, 30, 0.7);
opacity: 1;
}
<figure class="caption">
<img src="http://placehold.it/350x150">
<figcaption class="caption-text">Some text</figcaption>
</figure>