首页 > 解决方案 > 如何将色调(悬停时)应用于背景图像大小设置为包含的 div?

问题描述

我有一个带有背景图像的 div。由于设计限制,背景图像需要设置为包含的大小。我想在悬停时对该图像应用色调,但是我设置它的方式意味着整个 div 色调而不仅仅是图像。

我想知道是否有一种我不知道的 CSS 技术来实现我需要的效果,只有背景图像本身着色而不是整个 div?

.image {
  position: relative;
  padding-top: 50%;
  background-image: url('https://specials-images.forbesimg.com/imageserve/5f9cca07d4c42920d4d348c7/960x0.jpg?fit=scale');
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.image::before {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.3);
  opacity: 0;
  transition: ease opacity 350ms;
  z-index: 9;
  width: 100%;
  height: 100%;
}

.container:hover .image::before {
  opacity: 1;
}
<div class="container">
  <div class="image"></div>
</div>

标签: htmlcss

解决方案


.image {
  position: relative;
  padding-top: 50%;
  background-image: url('https://specials-images.forbesimg.com/imageserve/5f9cca07d4c42920d4d348c7/960x0.jpg?fit=scale');
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.image::before {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.3);
  opacity: 0;
  transition: ease opacity 350ms;
  z-index: 9;
  width: 100%;
  height: 100%;
}

.extraLayer {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: transparent;
  opacity: 0;
  transition: ease opacity 350ms;
  z-index: 10;
  width: 100%;
  height: 100%;
  text-align:center;
  margin-top:100px;
}
.container:hover .image::before {
  opacity: 1;
}

.container:hover .extraLayer {
  opacity: 1;
}
<div class="container">

  <div class="image"></div>
  <div class="extraLayer">
    <p style="color:white;">
      Draw what you want 
    </p>
</div>
</div>


推荐阅读