user2081044 user2081044 - 6 months ago 13
HTML Question

Three or more backgrounds stacked css

I'm trying to have three backgrounds stacked under each other using css but only two appear at maximum. Basically I want to make something like this:

enter image description here

Here is the code I'm using:

body{
font-size: 100%;
background-image: url(ex1.png), url(ex2.png), url(ex3.png);
background-repeat: no-repeat;
}


Is there any simple way to achieve this result using the body or am I forced to use divs instead?

Answer

When you set multiple images on a single element without specifying the background-position, they all are placed on the same position and so they will be one below the other. As long as the images are of the same size only one will show. If the images are of different size, say first is 100px tall, second is 200px, third is 300px then for the first 100px the first image will show up, for 100 - 200px the bottom of second image will show and for 200-300px the last third of the final image will show up.

Here is how you can stack the images within a single element. (Note: Height of the element should be equal to the height of all three images put together.)

div {
  height: 300px;
  width: 100px;
  background-image: url(http://lorempixel.com/100/100/nature/1), url(http://lorempixel.com/100/100/nature/2), url(http://lorempixel.com/100/100/nature/3);
  background-repeat: no-repeat;
  }
.bg-stack-with-pos {
  background-position: top, center, bottom;
}
.bg-stack-without-pos-diff-height {
  background-image: url(http://lorempixel.com/100/100/nature/1), url(http://lorempixel.com/100/200/nature/2), url(http://lorempixel.com/100/300/nature/3);
}
<h3>Stacked Images with Background Position - One below the other</h3>
<div class='bg-stack-with-pos'></div>
<h3>Stacked Images w/o Background Position - One behind the other</h3>
<div class='bg-stack-without-pos'></div>
<h3>Stacked Images w/o Background Position and different heights - One behind the other</h3>
<div class='bg-stack-without-pos-diff-height'></div>

Comments