在非Webkit浏览器中组合渐变和背景图像?

时间:2013-05-07 13:51:27

标签: css

我正在尝试组合透明的CSS渐变和背景图像,并且在不支持渐变的浏览器中优雅地失败。

我有这个CSS,它在Webkit浏览器中运行良好,但似乎被非Webkit浏览器(例如Firefox)完全忽略,它显示白色背景:

body {
  height:100%;
  -webkit-font-smoothing: subpixel-antialiased;
  padding-top: 2%;
  padding-bottom: 2%;
  background: -webkit-gradient(linear, left top, right top,
    from(rgba(0,0,0,0.4)), to(rgba(0,0,0,0.4)),
    color-stop(0.03, rgba(0,0,0,0.2)),
    color-stop(0.06, transparent),
    color-stop(0.94, transparent),
    color-stop(0.97, rgba(0,0,0,0.2))),
     url(../img/myimg.jpg) repeat;
}

但是,如果我将背景设置为:

  background: url(../img/myimg.jpg) repeat;

相反,它在Firefox中运行良好。 Firefox不应该忽略规则的-webkit-gradient部分吗?我怎样才能使这个Firefox友好?

3 个答案:

答案 0 :(得分:2)

你应该尝试使用标准的,没有前缀的线性渐变语法 - 现在是quite widely supported:IE10,chrome 26(当前是27),firefox 16(当前是20),opera 12.1(最新版本) 。要支持移动浏览器,您还需要以webkit为前缀的版本。

使用示例渐变,标准语法是......

background: linear-gradient(to left, 
    rgba(0,0,0,0.4), rgba(0,0,0,0.0) 6%, rgba(0,0,0,0.0) 94%, rgba(0,0,0,0.4));

您可以在a jsfiddle example中看到这一点。

答案 1 :(得分:1)

如果值无效,firefox将不会读取任何内容;这里你的背景被忽略了,因为-webkit是firefox的一个未知属性值,所以在你的例子中,-webkit首先是firefox的一个未知值,所以它会跳过它并转移到该类的下一个属性..例如

background: asadsa, url('http://images.google.co.in/intl/en_ALL/images/logos/images_logo_lg.gif'); 
/* asadsa is invalid here, so firefox will skip to next property */

Demo

CSS

div {
    background: asadsa, url('http://images.google.co.in/intl/en_ALL/images/logos/images_logo_lg.gif');
                ---^---
  /* Invalid Value For Property background */ 
    height: 200px;
    width: 300px;
    border: 1px solid #f00;
}

答案 2 :(得分:1)

Firefox不仅忽略规则的“那部分”。当Firefox无法识别其中的一部分时,它会忽略整个规则。

这意味着您可以指定多个规则,Firefox只会选择它理解的规则:

body {
  height:100%;
  -webkit-font-smoothing: subpixel-antialiased;
  padding-top: 2%;
  padding-bottom: 2%;
  background: url(http://lorempixel.com/400/200/) repeat;
  background: -webkit-gradient(linear, left top, right top,
    from(rgba(0,0,0,0.4)), to(rgba(0,0,0,0.4)),
    color-stop(0.03, rgba(0,0,0,0.2)),
    color-stop(0.06, transparent),
    color-stop(0.94, transparent),
    color-stop(0.97, rgba(0,0,0,0.2))),
     url(http://lorempixel.com/400/200/) repeat;
}

小提琴: http://jsfiddle.net/yb5AE/

Firefox了解第一个background规则,但不是第二个规则。因此使用第一个。 Webkit理解两者,因此第二个覆盖第一个,因为它被声明为“稍后”,因此使用第二个。