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

Time:06-15

The image can be show and hidden by an button. How do I style the image so it always shows up in the middle of the users screen. I work with position:absoulte;!

CodePudding user response:

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.

CodePudding user response:

For proper alignment of an element, i would suggest u use a flexbox.

This enables proper vertical and horizontal alignment, so you can at last easily center your element.

To center an element with flexbox we use the align-items for vertical alignment and justify-content for horizontal alignment.

Take a look at an example below.

// Select element with querySelector() method which returns the first element that matches a CSS selector.
const img = document.querySelector('img');
const button = document.querySelector('button');

// The addEventListener method attaches an event handler to an element (button).
button.addEventListener('click', function() {
  img.classList.toggle('hide');
});
.container{
  position: relative;
  width: 100%;
  height:100%;
}
.img-wrapper {
  display: flex;
  
  align-items: center;
  justify-content: center;
}

img.hide {
  display: none;
}

.btnClick{
  display: flex;
  margin: 5px auto;
}
<div >
  <div >
    <img src="https://picsum.photos/id/237/300/200">
  </div> 
  <button >Click to show/hide image</button>
</div>

CodePudding user response:

If I understand correctly, you want to center an element with position: absolute.

Here is how you can do that:

.some-element {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
  • Related