CSS - Inheriting layered background images

2019-04-19 18:16发布

CSS3 supports multiple background images, for example:

foo { background-image: url(/i/image1.jpg), url(/i/image2.jpg); }

I'd like to be able to add a secondary image to an element with a class though.

So for example, say you have a nav menu. And each item has a background image. When a nav item is selected you want to layer on another background image.

I do not see a way to 'add' a background image instead of redeclaring the whole background property. This is a pain because in order to do this with multi-backgrounds, you would have to write the base bg image over and over for each item if the items have unique images.

Ideally I'd be able to do something like this:

li { background: url(baseImage.jpg); }
li.selected { background: url(selectedIndicator.jpg); }

And have li.selected's end result appear the same if I did:

li.selected { background: url(baseImage.jpg), url(selectedIndicator.jpg); }

Update: I also tried the following with no luck (I believe backgrounds are not inherited..)

li { background: url(baseImage.jpg), none; }
li.selected { background: inherit, url(selectedIndicator.jpg); }

2条回答
\"骚年 ilove
2楼-- · 2019-04-19 18:55

I don't think this is possible, I think you'd have to redefine the whole rule every time.

For example, you could just add a "wrapper" around every item that has the initial background, with the actual item having a transparent background. Then add the background on the item itself when it's selected.

查看更多
Evening l夕情丶
3楼-- · 2019-04-19 19:12

That is, in any case, not the way CSS inheritance works. inherit implies that an element should take on the attributes of it's parent element, not previous declarations affecting the same element.

What you want has been proposed as a way to make CSS more object-oriented, but the closest you will get is with a pre-processor like SASS.

For now you actually just have to re-state the first image along with the second.

查看更多
登录 后发表回答