Paul
Paul

Reputation: 3368

Cannot get an image in a keyframe to center horizontally

I am having a huge headache with an image I have. It will not center horizontally no matter what I do. I have tried setting it to absolute and relative. Setting left to 50%, adding in transform: translate(-50%, -50%);, setting the image to display as block with the margin on the left and right as auto.

What else can I do to get this thing centered? Whenever I added transform: translate(-50%, -50%);, it centered, but the keyframe rotate got all out of wack and instead of the hand waving in the same position, the hand moved down the page.

The snippet does not fully demonstrate what it is doing.

.red {
  background-color: #0085A1;
  width: 100%;
  height: 100vh;
  position: relative;
  text-align: center;
}

.hand {
  width: auto;
  height: auto;
  position: absolute;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  position: absolute;
  /*transform: translate(0, -50%);*/
  /*transform: translate(-50%, -50%);*/
  top: 50%;
  left: 50%;
  margin-right: -50%;
  -webkit-animation: wave 4s 1 normal forwards;
  animation: wave 4s 1 normal forwards;
}

img.hand {
  display: block;
  margin-left: auto;
  margin-right: auto;
}

@keyframes wave {
  50% {
    -ms-transform: rotate(75deg);
    /* IE 9 */
    -webkit-transform: rotate(75deg);
    /* Chrome, Safari, Opera */
    transform: rotate(75deg);
  }
  90%,
  100% {
    opacity: 0
  }
}
<div class="red">
  <img class="hand" alt="HELLO">
</div>

Upvotes: 1

Views: 49

Answers (1)

Stickers
Stickers

Reputation: 78676

Add both translate() and rotate() at the same time.

jsfiddle

.red {
  background-color: #0085A1;
  width: 100%;
  height: 100vh;
  position: relative;
}
.hand {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%) rotate(0deg);
  animation: wave 4s 1 normal forwards;
}
@keyframes wave {
  50% {
    transform: translate(-50%, -50%) rotate(75deg);
  }
  100% {
    opacity: 0
  }
}
<div class="red">
  <img src="http://i.imgur.com/ywCRl0A.png" class="hand" alt="HELLO">
</div>

Upvotes: 2

Related Questions