Search code examples
imagestackz-index

How to place images on top of each other relative to a div element?


I want to stack images on top of each other relative to the div element they are in.

All the answered questions I've seen only stack elements on a blank page. My images need to remain in this div container tag, so setting my position to absolute would not work here.

Example code to use (none of the images belong to me): https://jsfiddle.net/Jonjei/3qymLn8v/4/

Any other general suggestions or tips are more than welcome as well.

HTML

<!-- images are placeholders and belong to their respective owners -->
<div class="container">

<img class="dog1" src="https://is3-ssl.mzstatic.com/image/thumb/Purple5/v4/da/83/ae/da83ae00-d126-1200-1588-c74c59aa1a38/source/256x256bb.jpg" alt="">

<img class="dog2" src="https://www.petmd.com/sites/default/files/petmd-puppy-weight.jpg" alt="">

<img class="dog3" src="https://vetstreet-brightspot.s3.amazonaws.com/56/d831705c9f11e19be6005056ad4734/file/puppy_training-tips-335mk022012-200454626-001.jpg" alt="">

</div>

CSS

.dog1 {
    position: relative;
    top: 0;
    left: 0;
    z-index: auto;
}

.dog2 {
    position: relative;
    top: 0px;
    left: 0px;
    z-index: 1;
}

.dog3 {
  position: relative;
    top: 0px;
    left: 0px;
    z-index: 2;
}

.container {
    background-color: #afbed8;
    border: 5px transparent solid;
    border-radius: 2px;
    margin: 2% 10% 2% 10%;
    padding: 0px 7% 0px 7%;
}

Solution

  • If you know your image sizes, you can give them negative top values;

    .dog2 {
        position: relative;
        top: -260px;
        left: 0px;
        z-index: 1;
    }
    
    .dog3 {
      position: relative;
        top: -619px;
        left: 0px;
        z-index: 2;
    }
    

    Or you can give your .container div a fixed height and set the dogs to position: absolute;