[Solved] How to center an hidden/visible element so it always shows up in the middle of the screen?


You need position fixed not absolute to get it centered on the viewport rather than on the body.

But you also need to make sure the the img is not a child of another transformed etc. element beneath body otherwise it will position fixed to that. See MDN

Here’s a simple example of making sure the img is centered on the viewport:

const img = document.querySelector('img');
const button = document.querySelector('button');
button.addEventListener('click', function() {
  img.classList.toggle('hide');
});
img {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 20vw;
}

img.hide {
  display: none;
}
<img src="https://picsum.photos/id/1015/200/300">
<button>Click to hide/unhide the image</button>

Note that there are several ways of hiding an element: display none which removes it more or less entirel; visibility hidden which keeps the space it was occupying – though in this case it does not matter in the way it would if the element were not fixed.

solved How to center an hidden/visible element so it always shows up in the middle of the screen?