试图将背景图像放在颜色上

时间:2014-03-11 23:17:08

标签: javascript css html5 css3

我试图将图像放在彩色背景上。一开始,我认为这是有效的:

background: white, url(example.png);

然而,根据the spec,这不是有效的。我必须输入<bg-image>,所以我必须使用我想要的颜色创建1x1图像,或者在两端创建具有相同颜色的use a gradient

background: linear-gradient(0deg, rgb(255,255,255) 0%, rgb(255, 255, 255) 100%), url(example.png);

我没想到它不接受white作为有效值。这绝对让我感到惊讶。

有没有办法在不创建无用渐变的情况下达到相同的效果?


如果我将background-color设置为white,结果将是这样的:

enter image description here

奖金代码:

padding: 2,
backgroundColor: "white",
backgroundImage: "url(url.png)",
backgroundPosition: "-168px -144px",
backgroundClip: "content-box",
backgroundRepeat: "no-repeat"
//I'm setting all these with JavaScript

任何可以达到我想要做的效果的答案都可以。

3 个答案:

答案 0 :(得分:2)

你必须混合使用长手乐谱和短手乐谱。此外,您需要为background-clip

设置多个属性
div {
    background: url(https://fbstatic-a.akamaihd.net/rsrc.php/v2/yl/r/djWWR4XJTnA.png), white;
    background-position: -168px -144px;
    background-clip: content-box, border-box;
    background-origin: border-box;
}

fiddle

这样,您的图像会在内容框中剪切,而白色背景会在边框框中剪切。此外,纯色必须是最后一个。

答案 1 :(得分:1)

您正在尝试使用背景的简写表示法,并且规范列出了简写符号。

http://www.dustindiaz.com/css-shorthand/

从您粘贴的代码中删除逗号,它会起作用。

答案 2 :(得分:0)

您只需要更改顺序,至少在Chrome中读取背景,如下所示:

  background: url('/example'), white
   background-image: url('/example')
   ...
   background-color: white