Search code examples
csscss-position

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?


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);
    }