Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Center a div in the screen regardless of origin

I have a lot of divs in a flexbox and when I click on one, I want it to scale up and then center itself in the viewport regardless of where it started (row/col). I have tried this with the typical "center a div" code, but its positioning is not even consistent across each div in the flexbox, let alone in the center. I am not completely against using JS, but I feel that there must be a pure CSS way to do this. Current attempt:

.selector {
    left: 50%;
    top: 50%;
    transform: translate(-50%, 0) scale(2);
}

which leads to any div being scaled up and moved to the right of its starting position.
Is there a way, or is JS my only option here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The most important addition would be position: fixed to have it centered in the viewport/window, regardless of the HTML structure. And change translate(-50%, 0) to translate(-50%, -50%), otherwise it won’t get centered vertically:

.selector {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%) scale(2);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading