首页 > 解决方案 > 将背景图像转换为灰色

问题描述

试图使背景图像平滑地淡出为透明,文本不透明度保持不变,但是我只管理了一个开/关过渡。不透明的过渡在这里不起作用,因为我需要文本保持不透明。任何想法如何做到这一点?

这是我的代码:

.grid {
  margin: 0;
  padding: 0;
  width: 500px;
  height: 250px;
}

.flexbox {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  overflow: hidden;
}

#one {
  width: 250px;
  height: 250px;
  background-color: red;
  background: url('https://doorcountypulse.com/wp-content/uploads/2018/03/1-PP-3-9-18-Raccoon-at-cracked-corn-660x440.jpg');
  background-repeat: no-repeat;
  background-position: 40%;
}

#one:hover {
  background: linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5)), url('https://doorcountypulse.com/wp-content/uploads/2018/03/1-PP-3-9-18-Raccoon-at-cracked-corn-660x440.jpg');
  background-repeat: no-repeat;
  background-position: 40%;
  height: 250px;
}
<div class="grid">
  <div class="flexbox">
    <div id="one">
      <div id="textbox">
        I need this picture to smoothly fade into transparent (grey) and this text to stay opaque.
      </div>
    </div>
  </div>
</div>

标签: htmlcssbackground-imagetransition

解决方案


您可以尝试使用 :: after 标记,这将帮助您完成您的预期。

您必须记住 content = "",否则图片将不会出现。还要记住正确设置负责图层位置的 z-index。

这是您的示例的解决方案:

.grid {
  margin: 0;
  padding: 0;
  width: 500px;
  height: 250px;
}

.flexbox {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  overflow: hidden;
}

#one {
  width: 250px;
  height: 250px;
  position: relative;
}

#one::after {
  position: absolute;
  z-index: 1;
  width: 100%;
  height: 100%;
  background: url('https://doorcountypulse.com/wp-content/uploads/2018/03/1-PP-3-9-18-Raccoon-at-cracked-corn-660x440.jpg');
  background-repeat: no-repeat;
  background-position: 40%;
  left: 0;
  top: 0;
  content: "";
transition: opacity 0.3s, visibility 0.3s;
}

#textbox {
  z-index: 2;
  position: relative;
}

#one:hover::after {
  opacity: 0;
  transition: opacity 0.3s, visibility 0.3s;
}
<div class="grid">
  <div class="flexbox">
    <div id="one">
      <div id="textbox">
        I need this picture to smoothly fade into transparent (grey) and this text to stay opaque.
      </div>
    </div>
  </div>
</div>


推荐阅读