Home > Blockchain >  Centring a .png with a high z-index within a div
Centring a .png with a high z-index within a div

Time:04-01

I want to have a .png image to be 1) exactly in the centre of a div, no matter the device size and 2) to be above another .png image in the same div. Here is my html:

 <div >
   <div id="spinningDial">
     <img src="redphone.png" id="phone"/>
     <img src="RadialSlime.png" id="radial"  style="width: 100%;">
   </div>
</div>

And here is my CSS:

 #phone {
      position: absolute;
      left: 67%;
      top: 45%;
      z-index: 10;
      opacity: 100%;
      width: 200px;
      }

The redphone.png is the image I'm referring to in my specifications above.

Using position: absolute; and z-index: 10; seems like the only way I get the .png to be above the other image, but it seems to place it outside the div. Whereas using, say, position: relative; with the same z-index displaces the png above the other image but keeps it contained in the same div.

This is the web page, if anyone wants to view the page source and see all the code.

CodePudding user response:

You can try adjusting the left and top to 50%, but also add transform: translate(-50%, -50%);. Result:

 #phone {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 200px;
}
 <div >
   <div id="spinningDial">
     <img src="https://upload.wikimedia.org/wikipedia/commons/9/9a/Gull_portrait_ca_usa.jpg" id="phone"/>
     <img src="https://cdn.i-scmp.com/sites/default/files/styles/landscape/public/d8/yp/images/shutterstock_259160825.jpg?itok=y8bw_02m" id="radial"  style="width: 100%;">
   </div>
</div>

CodePudding user response:

What you need is to put position relative to the parent to take the parent as a repair. Then to set a position of top and left to 50% to the phone, and as you see there, the position is not exactly on the center because of the picture dimensions. To fix this, you use then a transform to decrease top and left with half of picture's dimensions.

In final, you would have this in your CSS:

#spinningDial {
      position: relative;
}

#phone {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      z-index: 10;
      opacity: 100%;
      width: 200px;
}
  • Related