csscss-positionstacking-context

CSS position question. I want to put two images together on the same position


I want to put two images together like enter image description here with responsive. I used relative position for this, but whenever screen become smaller, it goes like this enter image description here I want to use two different images because I'm gonna animate these seperately.

.img_box{
   width: 100%
}

.desk {
  position: relative;
  width: 90%;
  bottom:-30%;
 
}

.person {
  position: relative;
  width: 90%;
  bottom:20%;
  right: 25%;
}
<div class="img_box">
  <img class="desk" src="https://material.angular.io/assets/img/examples/shiba1.jpg">
  <img class="person" src="https://material.angular.io/assets/img/examples/shiba2.jpg">
</div>

I tried to use absolute, but it doesn't work well for responsive I think


Solution

  • I would suggest creating a new stacking context by adding position: relative; to your .img_box wrapper element, then absolutely position any images ("layers") that you use inside of that new stacking context.

    For example:

    .img_box {
      /* Setting to position: relative creates a new stacking context */
      position: relative;
      width: 100%;
      max-width: 400px;
    }
    
    .img_layer {
      /* Positions absolutely each payer inside the .img_box stacking context */
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
    }
    
    .person {}
    .desk {}
    <div class="img_box">
      <img class="img_layer desk" src="https://assets.codepen.io/817230/back.gif">
      <img class="img_layer person" src="https://assets.codepen.io/817230/front.gif">
    </div>

    This way, adding position: absolute; to any layers will set their position relative to their parent (and not the document). You will be able to position/scale your wrapper element however you'd like and all children will follow suit accordingly.

    You can still use .person and .desk for additional styling on the respective layers and/or setting z-index, etc., which is why I left them.