且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用 rgba 背景颜色覆盖背景图像

更新时间:2022-03-02 23:49:31

PeterVR 的解决方案的缺点是额外的颜色显示在整个 HTML 块的顶部 - 这意味着它也显示在 div 内容的顶部,而不是就在背景图像的顶部.如果您的 div 为空,这很好,但如果它不使用线性渐变可能是更好的解决方案:

The solution by PeterVR has the disadvantage that the additional color displays on top of the entire HTML block - meaning that it also shows up on top of div content, not just on top of the background image. This is fine if your div is empty, but if it is not using a linear gradient might be a better solution:

<div class="the-div">Red text</div>

<style type="text/css">
  .the-div
  {
    background-image: url("the-image.png");
    color: #f00;
    margin: 10px;
    width: 200px;
    height: 80px;
  }
  .the-div:hover
  {
    background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
    background-image: -moz-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
    background-image: -o-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
    background-image: -ms-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
    background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(0, 0, 0, 0.1)), to(rgba(0, 0, 0, 0.1))), url("the-image.png");
    background-image: -webkit-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
  }
</style>

参见 fiddle.太糟糕了,梯度规范目前一团糟.请参阅 兼容性表,上面的代码应该可以工作在任何具有显着市场份额的浏览器中 - MSIE 9.0 和更早版本除外.

See fiddle. Too bad that gradient specifications are currently a mess. See compatibility table, the code above should work in any browser with a noteworthy market share - with the exception of MSIE 9.0 and older.

编辑(2017 年 3 月):网络状态现在变得不那么混乱了.所以 linear-gradient(Firefox 和 Internet Explorer 支持)和 -webkit-linear-gradient(Chrome、Opera 和 Safari 支持)行就足够了,额外的前缀版本不再需要.

Edit (March 2017): The state of the web got far less messy by now. So the linear-gradient (supported by Firefox and Internet Explorer) and -webkit-linear-gradient (supported by Chrome, Opera and Safari) lines are sufficient, additional prefixed versions are no longer necessary.