Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS - Inheriting layered background images

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); }
like image 274
NNN Avatar asked Apr 01 '10 23:04

NNN


People also ask

Can you layer background images CSS?

CSS allows you to add multiple background images for an element, through the background-image property. The different background images are separated by commas, and the images are stacked on top of each other, where the first image is closest to the viewer.

How do I stop an image from repeating in CSS?

If you want the background image not to repeat at all, use background-repeat: no-repeat; .

Is background color inherited in CSS?

Background properties do not inherit, but the parent element's background will shine through by default because of the initial 'transparent' value on 'background-color'. In terms of the box model, "background" refers to the background of the content and the padding area.


2 Answers

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.

like image 54
Miriam Suzanne Avatar answered Sep 23 '22 14:09

Miriam Suzanne


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.

like image 44
Chad Birch Avatar answered Sep 21 '22 14:09

Chad Birch