问题
I have two pairs of images that need to be displayed in a div. The images are each 280px wide by 200px high. I need the second pair to be displayed below (after) the first pair in the container div. Here is my code:
<div>
<div style="position:relative; z-index:1;">
<img alt="background 1" src="background1.png" width="280" />
</div>
<div style="position:absolute; z-index:2;">
<img alt="overlay 1" src="overlay1.png" width="280" />
</div>
<div style="position:relative; z-index:3;">
<img alt="background 2" src="background2.png" width="280" />
</div>
<div style="position:absolute; z-index:4;">
<img alt="overlay 2" src="overlay2.png" width="280" />
</div>
</div>
I cannot figure out how to make overlay1.png display on top of background1.png, and overlay2.png to display on top of background2.png, and for the second set of images to be lower down on the page than the first set with a 10px gap between them.
Help! Thanks!
回答1:
It sounds to me you're looking for something more like this:
<div style="position:relative; z-index:1;">
<img alt="background 1" src="background1.png" width="280" style="position:absolute; z-index:2;"/>
<img alt="overlay 1" src="overlay1.png" width="280" />
</div>
<div style="position:relative; z-index:3;">
<img alt="overlay 2" src="overlay2.png" width="280" style="position:absolute; z-index:4;"/>
<img alt="background 2" src="background2.png" width="280" />
</div>
Also, inline styles are not good practice unless you're designing emails.
Here's a more complete example using css: Live demo (click).
Markup:
<div class="parent">
<img alt="overlay 1" src="http://placehold.it/280x100/f9ff9f">
<img alt="background 1" src="http://placehold.it/280x100">
</div>
<div class="parent">
<img alt="background 2" src="http://placehold.it/280x100/f9ff9f">
<img alt="overlay 2" src="http://placehold.it/280x100">
</div>
CSS:
.parent {
position: relative;
z-index: 1;
margin-bottom: 10px;
}
.parent > img {
width: 280px;
z-index: 2;
}
.parent > img:first-child {
position: absolute;
}
/* so you can see that they are overlayed */
.parent > img:first-child {
width: 240px;
height: 60px;
margin: 20px;
}
回答2:
this will work:
<div>
<div style="position:absolute; z-index:1; top: 0;">
<img alt="background 1" src="background1.png" width="280" />
</div>
<div style="position:absolute; z-index:2; top: 0;">
<img alt="overlay 1" src="overlay1.png" width="280" />
</div>
<div style="position:absolute; z-index:3; top: 290px;">
<img alt="background 2" src="background2.png" width="280" />
</div>
<div style="position:absolute; z-index:4; top: 290px;">
<img alt="overlay 2" src="overlay2.png" width="280" />
</div>
</div>
i changed them all to position absolute and added css-top-rules
来源:https://stackoverflow.com/questions/20886292/stacking-multiple-images-with-z-index