How can I overlay multiple images using HTML/CSS o

2019-04-15 04:32发布

问题:

I am a Google lover, and as thus I've hunted around pretty thoroughly before arriving here. Perhaps I'm just being inattentive, or my skimming habit is coming back to bite me, but I don't believe I've found the answer yet.

I've seen solutions to similar problems, but I don't think any of them are applicable here. I want to overlay two PNGs of the same size in an element; this in itself is simple, but the context is a little more complex. I've worked with HTML/CSS for a long time now, and I'm learning JavaScript currently; as such, I've been making an HTML game. This game involves creating animals with different characteristics, and I've drawn PNGs for each of the characteristics and saved them separately with transparent backgrounds. Here, for reference, is an example:

The base image:

Eyelashes I want to overlay for female frogs:

I am familiar with using position:absolute to overlay images, but I can't give an absolute position; the creatures will be displayed automatically to a div alongside each other using innerHTML, which presents two problems: one, not every creature will be in the same absolute position, and two, some will not be visible until the user scrolls down. I've also thought about setting the background image as one image, but there will be scenarios which require the overlay of up to four individual images, so that wouldn't work. I've come across some mysterious possibilities regarding jQuery, but since I haven't gotten that far in my learning yet, I'd appreciate very much if someone is able to help me. The only other alternative is to manually overlay and save every possible combination as an image, which would require several hundred images, so I fervently hope I can avoid that path at all costs.

If I'm just being stupid and the solution is already in one of the possibilities I've considered and discarded, please let me know.

回答1:

If you can't position it absolute I think the only solution are multiple backgrounds (CSS3):

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_multiple_backgrounds

http://www.css3.info/preview/multiple-backgrounds/

The problem comes when you need to add or remove specific backgrounds... you'll need specifically created functions to add backgrounds and remove them from the layer.

BTW, I recommend you trying to move them to an absolute position, as it will be easier than using multiple backgrounds.

Remember that you can use position: absolute inside a relative-positioned div, so the absolute positioning will be relative to the relative-positioned one.