Home > Enterprise >  How do I overlay two images but position it so it looks like one?
How do I overlay two images but position it so it looks like one?

Time:10-01

Is it possible to position one image ontop of another image, using just CSS, so that even when image gets scaled / window gets resized, the images will be in the same relative position? So to the user, it pretty much looks the same as if it was one flat image.

Example, in this code snippet, I have a red dot and a dog picture, depending on the window size, the red dot should be somewhere in the dog's left ear. I would like it to stay exactly in that same place (respective to the background picture), no matter how big or small the dog picture gets scaled. By that I mean, the actual position will change, but since the picture got bigger, it moves to the right location, so visually it did not move.

<style>
.container {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 200px;
}
.myDiv {
  height: 100%;
  width: 100%;
  background-image: url('https://toppng.com/uploads/preview/red-dot-icon-png-bowling-ball-transparent-background-11562953794gu3xfby6c8.png'), url('https://image.freepik.com/free-photo/selective-focus-shot-adorable-kooikerhondje-dog-field_181624-29383.jpg');
  background-size: 5% auto, cover;
  background-repeat: no-repeat;
  background-position: 50% 75%, 0 0;
  background-blend-mode: normal;
}
</style>
<div class="container>
  <div class="myDiv" />
</div>

My attempt at it was using percentages for everything (background size, and position). I figured as the picture gets scaled, so would the position, but it's not working as expected.. the red dot sometimes would be outside the dog's ear, or just in a different spot within the ear.

CodePudding user response:

Absolutely position your ball png and use percentage values for your top and left properties. As long as all your dimensions are percentages all your elements will scale proportionally.

You can use decimals for your positions too (e.g top:20.25%) to get it in exactly the right place if necessary.

.container {
  width:70%;
  margin:auto;
  position:relative;
}

.container img.under {
  width:100%;
  height:auto;
}
.container img.over {
  position:absolute;
  top:20%;
  left:45%;
  z-index:1;
  width:10%;
  height:auto;
}
<div class="container">
  <img class="over" src="https://toppng.com/uploads/preview/red-dot-icon-png-bowling-ball-transparent-background-11562953794gu3xfby6c8.png" />  
  <img class="under" src="https://image.freepik.com/free-photo/selective-focus-shot-adorable-kooikerhondje-dog-field_181624-29383.jpg" />  
</div>

  • Related