css鼠标悬停时文字覆盖图片

作者: xusx 分类: Web 发布时间: 2022-05-08 18:06 浏览:405

下面实现悬停时的图像叠加文字的效果。

步骤

  • 分别对叠加层的顶部和底部条使用 :before:after 伪元素。 设置它们的不透明度 opacity 、缩放变换 transform 和 过渡动画 transition 以产生所需的效果。
  • 使用 figcaption 标签作为覆盖的文本。 设置 display: flex; flex-direction: column; justify-content: center 使文本居中到图像中。
  • 使用 :hover 伪选择器更新所有元素的不透明度和变换并显示覆盖。

效果

HTML

<figure class="hover-img">
  <img src="https://xushanxiang.com/media/xu.jpg"/>
  <figcaption>
    <h3>许善祥</h3>
  </figcaption>
</figure>

CSS

.hover-img {
  color: #fff;
  display: inline-block;
  margin: 8px;
  max-width: 320px;
  min-width: 240px;
  overflow: hidden;
  position: relative;
  text-align: center;
  width: 100%;
}

.hover-img * {
  box-sizing: border-box;
  transition: all 0.45s ease;
}

.hover-img:before,
.hover-img:after {
  background-color: rgba(100, 100, 100, 0.5);
  border-top: 64px solid rgba(100, 100, 100, 0.5);
  border-bottom: 64px solid rgba(100, 100, 100, 0.5);
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  content: '';
  transition: all 0.3s ease;
  z-index: 1;
  opacity: 0;
  transform: scaleY(2);
}

.hover-img img {
  vertical-align: top;
  max-width: 100%;
  backface-visibility: hidden;
}

.hover-img figcaption {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  align-items: center;
  z-index: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  line-height: 1.1em;
  opacity: 0;
  z-index: 2;
  transition-delay: 0.1s;
  font-size: 24px;
}

.hover-img:hover:before,
.hover-img:hover:after {
  transform: scaleY(1);
  opacity: 1;
}

.hover-img:hover > img {
  opacity: 0.6;
}

.hover-img:hover figcaption {
  opacity: 1;
}

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!