CSS背景颜色不透明度

时间:2018-08-07 12:56:26

标签: html css background-color

当有人将鼠标悬停在按钮上时,我想为按钮添加深色的背景颜色。我的问题是,默认情况下(未悬停时)按钮具有background-color: transparent

因此,这意味着按钮具有不同的背景颜色(取决于背景div的颜色)。因此,我不能为每种深色设置20个以上的CSS类。我想要一个可以添加到单个图标按钮类的解决方案。请参阅我的示例以获得更好的解释。

我想要这样的东西:

.icon-button:hover {
    background-color: black;
    background-color-opacity: 25%;
}

代替这样做:

.icon-button.white:hover {
    background-color: #xxxxxx; (darkened white)
}

.icon-button.red:hover {
    background-color: #xxxxxx; (darkened red)
}

.icon-button.purple:hover {
    background-color: #xxxxxx; (darkened purple)
}

.icon-button.green:hover {
    background-color: #xxxxxx; (darkened green)
}

.....

(由于某种原因,我的图片上传失败,请在此处进行检查) https://i.imgur.com/5HSzxqF.jpg

1 个答案:

答案 0 :(得分:2)

您可以使用rgba颜色作为背景。 rgba具有一个Alpha通道,该通道指示颜色层的不透明度。这相当于您提到的background-color-opacity

div {
  padding: 15px;
  text-align: center;
}
div:nth-child(1) {
  background: red;
}

div:nth-child(2) {
  background: green;
}

div:nth-child(3) {
  background: blue;
}

button {
  background: transparent;
  border: 1px solid white;
  color: white;
  padding: 15px 30px;
  transition: all .2s ease;
}

button:hover {
  background: rgba(0,0,0,0.3);
}
<div>
  <button type="button">
    Button
  </button>
</div>

<div>
  <button type="button">
    Button
  </button>
</div>

<div>
  <button type="button">
    Button
  </button>
</div>

相关问题