Make element expand from its center

1

The problem is: I have a% centralized% with that container trick in div or position: absolute and fixed internal in div .

As you can see, when the animation is executed, the% s of internal% (#square) grows from top to bottom. I would like it to grow from its center and expand to all sides, but it stays the same distance from the top, because of relative . What can I do so that, in animation, it expands to all sides, rather than up and down?

// Função simples para animar a div com css transitions
var square = document.querySelector('#square');

setTimeout(function(){
      square.style.width = '100px';
      square.style.height = '100px';
}, 500);
#container {
      position: fixed;
      left: 50%;
      top: 50%;
}

#square {
      position: relative;
      left: -50%;
      top: -30%;
      width: 20px;
      height: 20px;
      background: blue;
      transition: all 1s ease-in-out;
}
<div id="container" >
    <div id="square" > </div>
</div>
    
asked by anonymous 10.07.2017 / 02:59

1 answer

2

A simple solution is to use scale instead of modifying width and height :

// Função simples para animar a div com css transitions
var square = document.querySelector('#square');

setTimeout(function(){
      square.style.transform = "scale(5)"; //scale em vez de width e height
      //scale(5) dá 5 vezes o tamanho, logo 100 por 100.
}, 500);
#container {
      position: fixed;
      left: 50%;
      top: 50%;
}

#square {
      position: relative;
      left: -50%;
      top: -30%;
      width: 20px;
      height: 20px;
      background: blue;
      transition: all 1s ease-in-out;
      /*transform: scale(1); coloquei aqui para tornar claro que é o valor inicial, embora não seja necessário*/
}
<div id="container" >
    <div id="square" > </div>
</div>

To embed an image in the div it is best to have the transformation go from a value less than 0 to 1, so as not to distort. And define the actual dimension of the image in width and height .

Image solution:

// Função simples para animar a div com css transitions
var square = document.querySelector('#square');

setTimeout(function() {
    square.style.transform = "scale(1)"; //agora com 1 para ficar no tamanho real
}, 500);
#container {
            position: fixed;
            left: 50%;
            top: 10%; /*passou a 10% aqui*/
        }
        
        #square {
            position: relative;
            left: -50%;
            top: 0;
            width: 200px;
            height: 200px;
            transition: all 1s ease-in-out;
            background: url(https://upload.wikimedia.org/wikipedia/commons/6/6a/Culmination200.jpg);
            transform:scale(0.1); /*tamanho começa mais pequeno para não distorcer*/
        }
<div id="container">
    <div id="square"> </div>
</div>
    
10.07.2017 / 03:24