14

The title basically says it all.


Here's an example:

#element {
    background: url(image.png) no-repeat center center,
                linear-gradient(to top, #86a53c, #516520);
}

#element:hover {
    background: url(image.png) no-repeat center center,
                linear-gradient(to top, #A0C153, #516520);
}

#element:active {
    background: url(image.png) no-repeat center center,
                linear-gradient(to top, #516520, #A0C153);
}

As you can see, only one of the background images changes - the other one stays the same in each and every state, but is still being declared four times!

So, is it possible to only change one of the backgrounds, but leave the other one as is - without having to re-declare it over and over again?

I know that the other CSS background properties (repeat, position etc.) can be set separately. This is just a quick example...

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292

2 Answers2

5

Nope, no can do yet, sorry. This sounds like an addition that you can propose, though I'm not sure how it'd play out in terms of syntax and the cascade.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • I can't even imagine what the syntax could be. I'm pretty jealous of anyone who actually gets to use multiple backgrounds in the first place, I'm still tied to IE7 support. Progressive enhancement? Sure, try telling the client that. – Wesley Murch Mar 23 '12 at 19:37
  • Disappointing, to say the least. As for syntax: why not use an array-like number? For example `background-image-1`, `background-image-2` etc. This would also be useful for `box-shadow`, or any any other CSS property that takes multiple values. As for the cascade: I see no problems whatsoever. Why should it be any different than [IE's `background-position-x` & `background-position-y`](http://snook.ca/archives/html_and_css/background-position-x-y)? – Joseph Silber Mar 25 '12 at 00:40
  • 1
    I'd be glad if there was a syntax like `background-position: , , 0 -20px, ;` to modify the position of the third background among four. – aaaaaa Aug 28 '12 at 19:24
3

This is now possible with CSS variables:

#element {
    --gradient: linear-gradient(to top, #86a53c, #516520);

    background: url(image.png) no-repeat center center,
                var(--gradient);
}

#element:hover {
    --gradient: linear-gradient(to top, #A0C153, #516520);
}

See it here in action: https://jsfiddle.net/22zu6oaq/

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • Yes, and the best thing about this is that it flies right in the face of the concerns I previously raised: "how it'd play out in terms of syntax and the cascade". [Here's](http://stackoverflow.com/questions/40010597/how-do-i-apply-opacity-to-a-css-color-variable/41265350#41265350) an even crazier example. – BoltClock Feb 13 '17 at 14:48