html - 在图像悬停时,覆盖原始图像并显示文本

标签 html css

当鼠标悬停在图像上时,我希望显示带有文本的辅助图像,但我的方法似乎无法正常工作。

我想如何想象:

红色为正常状态,右图为悬停状态。

enter image description here

这是我目前的做法:

.img-wrap {
  position: relative;
  height: 360px;
  width: 360px;
}

.img-description {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(29, 106, 154, 0.72);
  color: #fff;
  visibility: hidden;
  opacity: 0;
  transition: opacity .2s, visibility .2s;
}

.img-wrap:hover .img-description {
  visibility: visible;
  opacity: 1;
}
ul {
    list-style-type: none;
    margin: auto;
}
<div class="img-wrap">
  <ul class="clearfix">
    <li>
      <img src="https://cdn2.hubspot.net/hubfs/1878396/LR%20-%20Landing%20page%20images/LR%20-%20Scottish%20Campaign/large-cta.png?t=1528962213286" />
    </li>
  </ul>
  <img class="img-img" src="https://insights.zonal.co.uk/hubfs/LR%20-%20Landing%20page%20images/LR%20-%20Scottish%20Campaign/cta-bg.png" />
  <h2 class="img-description">TEST</h2>
  <span class="button large-cta-button">Read more</span>
</div>

最佳答案

对于透明颜色叠加层,您可以在 li 上使用伪元素,如 :after。这样它将始终保持在 li 和 img 之上。 img 应该有一个 max-width:100% 这样它就不会溢出它的父级 (li)。

然后,涉及一些非常简单的样式。您还可以添加一些关于蓝色叠加层应如何显示的动画,但这取决于您。

如有任何疑问,请在评论中提问。

.img-wrap {
  position: relative;
  height: 360px;
  width: 360px;
}

img {
  max-width: 100%;
  height: auto;
}

.img-wrap ul {
  padding: 0;
}

.img-wrap li {
  position: relative;
}

.img-wrap .img-description {
  position: absolute;
  opacity: 0;
  z-index: 2;
  transition: 0.3s ease-out;
  top: 50%;
  transform: translate(-50%, -50%);
  left: 50%;
  width:auto;
}

.img-wrap li .img-description h2 {
  margin-bottom: 50px;
}

.img-wrap li .img-description a {
  padding: 10px;
  color: #fff;
  border: 1px solid #fff;
}

.img-wrap li:after {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(29, 106, 154, 0.72);
  color: #fff;
  visibility: hidden;
  opacity: 0;
  transition: opacity .2s, visibility .2s;
  height: 100%;
  width: 100%;
  content: "";
}

.img-wrap:hover li:after {
  visibility: visible;
  opacity: 1;
}

.img-wrap:hover .img-description {
  opacity: 1;
}

ul {
  list-style-type: none;
  margin: auto;
}
<div class="img-wrap">
  <ul class="clearfix">
    <li>
      <img src="https://cdn2.hubspot.net/hubfs/1878396/LR%20-%20Landing%20page%20images/LR%20-%20Scottish%20Campaign/large-cta.png?t=1528962213286" />
      <div class="img-description">
        <h2>
          TEST
        </h2>
        <a>Test link</a>
      </div>
    </li>
  </ul>
</div>

关于html - 在图像悬停时,覆盖原始图像并显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50852429/

相关文章:

html - 更改宽度 css 时禁用文本框

javascript - 占据屏幕全宽的表单

javascript - 用于创建文本字段的下拉菜单

javascript - 如何让用户通过单击文本来增加字体大小?

html - Laravel:文本溢出:省略号不适用于显示未转义的数据

html - 边栏和内容上的独立 Overflow-y 滚动

HTML 页脚 CSS 设置

html - Twitter bootstrap 中的脚手架和网格系统

javascript - 将文字放在图像上并另存为图像

html - 在 Angular 中自定义 NG Bootstrap 轮播