首页 > 解决方案 > 在悬停按钮时在按钮上添加渐变而不影响文本

问题描述

我正在尝试在具有背景图像的按钮上添加渐变,同时将其悬停,而渐变不会影响/覆盖文本。

div.test {
  background-image: linear-gradient(to right, #f9f9f9, #a2a2a2, #f9f9f9);
  opacity: 0;
  position: absolute;
  width: 260px;
  height: 80px;
  margin-top: -23.5px;
  z-index: 2;
}

div.test:hover {
  opacity: 0.2;
}

div.menuleftbutton {
  position: absolute;
  width: 260px;
  height: 80px;
  margin: 150px 8% 0px;
  background-color: blue;  /* this would be replaced by an image */
}

div.menuleftbuttontext {
  margin: 23.5px 0px 23.5px;
  background-color: yellow;
  font-size: 33px;
  height: 33px;
}
<div class="menuleftbutton">
  <div class="menuleftbuttontext">
  <div class="test">
  </div>
    TEXT GOES HERE              
  </div>
</div>

jsfiddle 中的完整内容: https ://jsfiddle.net/fm6q95wk/1/

预期的结果是渐变被添加到文本“下方”,而这个版本没有。

到目前为止,我尝试过的每个版本要么在文本上放置渐变,要么在鼠标悬停在文本上时不显示渐变。

标签: css

解决方案


我已经修改了 HTML,所以你只有一个 inner 和一个 external div

我更改了 CSS,所以本质上内部 div 设置了外部 div 的宽度和高度。这是因为您希望悬停效果覆盖整个“按钮”,而我将悬停渐变放在内部 div 上,而外部 div 获取背景图像。阅读 CSS 中的注释,其中我解释了每个规则的作用。

注意 RGBA 在linear-gradient. 这样您就可以控制渐变的不透明度,我使用0.5了不透明度,以便在悬停时更容易看到变化,但您可以轻松地将其更改回 0.2 以获得确切的外观。如果需要,请访问: http ://hex2rgba.devoth.com/ 十六进制到 rgba 转换器。

* {
  box-sizing: border-box;
}
.menuleftbutton {
  position: absolute;
  background-image: url(https://picsum.photos/200); /* background-image */
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  margin: 0; /* just for the demo, change the margin to whatever you need */
  cursor: pointer; /* hover... this makes it feel much more like a button */
}

.menuleftbuttontext {
  width: 260px;
  height: 80px;
  font-size: 26px; /* decreased the size because it was splitting into 2 lines */
  padding: 0 20px; /* keep text from hitting sides */
  line-height: 80px; /* line-height same as height vertically centers text */
}

.menuleftbutton:hover .menuleftbuttontext { /* style of inner div when outer div is hovered */
  background-image: linear-gradient(to right, rgba(249, 249, 249, 0.5), rgba(162, 162, 162, 0.5), rgba(249, 249, 249, 0.5));
}
<div class="menuleftbutton">
    <div class="menuleftbuttontext">
      TEXT GOES HERE
    </div>
</div>


推荐阅读