Search code examples
csscss-transforms

Why the div is not centred


im triying to center this element in the screen, and also when i hover.

In my example below, the div is not centred, even when i hover it knowing that i made the transform 50% and top/left too, that's what i use uselly to center an element.

* {
  box-sizing: border-box;
}
body {
position: relative }

.zoom {
  padding: 50px;
  background-color: green;
  transition: transform .2s;
  width: 200px;
  height: 200px;
  margin: 0 auto;
  
  transform: scale(.2) translate(-50%, -50%);
  position: absolute;
      top: 50%;
    left: 50%;
}

.zoom:hover {
  -ms-transform: scale(1.5); /* IE 9 */
  -webkit-transform: scale(1.5); /* Safari 3-8 */
  transform: scale(1.5); 
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
 
</head>
<body>
 
<div class="zoom"></div>

</body>
</html>


Solution

  • Keep in mind the order of the transforms determines how the element appears. You first move the element top: 50%; left: 50%;, which puts it in the bottom right quadrant. Then you make it smaller transform: scale(0.2) and then you move it left by 50% of its now smaller size translate(-50%, -50%).

    By placing the translate first, the element is centered before becoming smaller. Remember to also include the translate(-50%, -50%) when you increase the size, as the consequent translates will overwrite the current one, not add to it.

    * {
      box-sizing: border-box;
    }
    html, body {
      height: 100%;
    }
    body {
    position: relative }
    
    .zoom {
      padding: 50px;
      background-color: green;
      transition: transform .2s;
      width: 200px;
      height: 200px;
      margin: 0 auto;
      
      transform: translate(-50%, -50%) scale(.2);
      position: absolute;
          top: 50%;
        left: 50%;
    }
    
    .zoom:hover {
      -ms-transform: translate(-50%, -50%) scale(1.5); /* IE 9 */
      -webkit-transform: translate(-50%, -50%) scale(1.5); /* Safari 3-8 */
      transform: translate(-50%, -50%) scale(1.5); 
    }
    <!DOCTYPE html>
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
     
    </head>
    <body>
     
    <div class="zoom"></div>
    
    </body>
    </html>