Search code examples
htmlcssimageanimationposition

How to fix the center of an image in one place for an animation?


img {
  width: 20px;
  height: auto;
  border-radius: 50%;
  margin-bottom: 5px;
  display: block;
  transition: all 0.5s ease-in-out;
}

img:hover {
  width: 200px;
  height: auto;
  border-radius: 0;
  transition: all 0.5s ease-in-out;
}
    <figure>
      <img
        src="https://i.sstatic.net/FuQYf.png"
        alt="This is a picture"
      />
    </figure>

I want to fix the center of this image in one place so that when the image grows, the expansion doesn't only happen in right direction, but both in the left and right directions, same for the upward and downward direction. (Here, it happens only in the downward direction.)

How do I do it? I tried setting margins to auto, but that centers the image the whole page, but I want it to be left aligned. Also, it doesn't seem to work for upward and downward direction.

Thanks!


Solution

  • You an achieve this by centering the image like this

    img {
      transform: translate(-50%, -50%);
    }
    

    img {
      width: 20px;
      height: auto;
      border-radius: 50%;
      margin-bottom: 5px;
      display: block;
      margin-top: 56px;
      margin-left: 52px;
      transform: translate(-50%, -50%);
      transition: all 0.5s ease-in-out;
    }
    
    img:hover {
      width: 200px;
      height: auto;
      border-radius: 0;
      transition: all 0.5s ease-in-out;
    }
        <figure>
          <img
            src="https://i.sstatic.net/FuQYf.png"
            alt="This is a picture"
          />
        </figure>