0

I followed Difference between style = "position:absolute" and style = "position:relative", where I understood that if the outer div is of relative position, then when you set the inner div to absolute position, it will be positioned according to the outer div.

Here is my code:

HTML:

<div class="sonar-wrapper">
  <div class="sonar-emitter">
    <div class="sonar-wave"></div>
  </div>
  <img src="https://sdl-stickershop.line.naver.jp/products/0/0/1/1034784/android/stickers/1469060.png" height="72 " width="72 " class="sooperIdea ">
</div>

CSS:

.sooperIdea {
  position: absolute;
  left: 44.5%;
  top: 29%;
}


/* Prevent scrollbars to appear when waves go out of bound */

.sonar-wrapper {
  position: relative;
  z-index: 0;
  //overflow: hidden;
}


/* The circle */

.sonar-emitter {
  position: relative;
  margin: 32px auto;
  width: 160px;
  height: 160px;
  border-radius: 9999px;
  background-color: HSL(45, 100%, 50%);
}

However, the image fails to stick to the center of the div when I minimize the width of my browser (trying to emulate a mobile device). If I get it around the center for a mobile, then it will be misplaced (not-centered) in full-screen mode in a PC.

Play around with it in the Live demo.

How to get the image on the center of the sun in both a PC and a mobile device?


PS: I also tried to place the image in a div, and apply the sooperIdea class there, instead of doing so in the image itself, but got the same results.

gsamaras
  • 71,951
  • 46
  • 188
  • 305

1 Answers1

2
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate( -50%, -50% );

Is the defacto CSS code I always use to both vertically and horizontally center elements within their parent.

If you remove the previous positioning code to the .sooperIdea class and add the above it works fine.

.sooperIdea {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate( -50%, -50% );
}


/* Prevent scrollbars to appear when waves go out of bound */

.sonar-wrapper {
  position: relative;
  z-index: 0;
  //overflow: hidden;
}


/* The circle */

.sonar-emitter {
  position: relative;
  margin: 32px auto;
  width: 160px;
  height: 160px;
  border-radius: 9999px;
  background-color: HSL(45, 100%, 50%);
}
<div class="sonar-wrapper">
  <div class="sonar-emitter">
    <div class="sonar-wave"></div>
  </div>
  <img 
    src="https://sdl-stickershop.line.naver.jp/products/0/0/1/1034784/android/stickers/1469060.png" 
    height="72 " width="72 " class="sooperIdea"
  >
</div>

Note that we add position: relative to the parent element to make sure the absolutely positioned child gets positioned relative to the parent

basement
  • 718
  • 8
  • 15