Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

Trying to put a background image on top of a color

I'm trying to put an image on top of a color background. In the beginning, I thought this is valid:

background: white, url(example.png);

However, according to the spec, this isn't valid. I must enter a <bg-image>, so I must either create a 1x1 image with the color I want, or use a gradient with the same color on two ends.

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

I did not expect it to not accept white as a valid value. This definitely surprised me.

Is there any way to achieve the same effect without creating a useless gradient?


If I set background-color to white, the result will be something like this:

enter image description here

Bonus code:

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

Any answer that can achieve the effect I'm trying to do is okay.

Upvotes: 3

Views: 81

Answers (3)

vals
vals

Reputation: 64164

Your have to mix both the long-hand notation and the short-hand notation. Also, you need to set multiple properties for 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

This way, your image is clipped at content box, and the white background at the border box. Also, the solid color must be the last.

Upvotes: 2

Diogo Almiro
Diogo Almiro

Reputation: 373

You just have to change the order, the background is readed at least in chrome like this:

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

Upvotes: 0

mchandleraz
mchandleraz

Reputation: 381

You're trying to use the shorthand notation for background, and the spec is listing the longhand notations.

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

Remove the comma from the code you pasted, and it'll work.

Upvotes: 1

Related Questions