是否可以使用以下代码在悬停时垂直居中标题?我知道我可以添加一个围绕figcaption标签的div来进行叠加,但我想知道在不添加更多HTML代码的情况下是否可以这样做。
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);
}
提前致谢
答案 0 :(得分:1)
您可以在.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>