Search code examples
csscss-animationsopacity

css animation-fill-mode foward changes element opacity


Having an issue with an image when upon the image finishes its animation and is filled in forwards, it's opacity is lower than if i just load the image normally (with the animations taken out)

.header-container .col-2 {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50%;
  z-index: -1;
}
.header-container .col-2 img {
  opacity: 0;                       //
  animation: 0.5 header ease 1.25s; // these three lines seem to be the problem
  animation-fill-mode: forwards;    //
}

@keyframes header {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

I have looked at the styles on my browser (chrome) and can't work out why this is happening In the image is what the difference looks like + chrome styles

img on right has slightly lower opacity

Thanks for any suggestions / help


Solution

  • animation: 0.5 header ease 1.25s;
    the 0.5 without the time unit is interpreted as the animation-iteration-count which, if set to 0.5 means: "Run my animation halfways."

    What you want is: name, duration, easing, delay, fill-mode use:

    animation: header 0.5s ease 1.25s forwards;
    

    and use the s or ms unit for the duration value.

    Here's a reminder for the Animation shorthand order:

    name, duration, easing, delay, iteration-count, direction, fill-mode

    .header-container .col-2 {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 50%;
      z-index: -1;
      background: url("https://placehold.it/100x100/00f");
    }
    .header-container .col-2 img {
      opacity: 0;                       
      animation: header 0.5s ease 1.25s forwards; 
    }
    
    @keyframes header {
      from {
        opacity: 0;
      }
      to {
        opacity: 1;
      }
    }
    <div class="header-container">
      <div class="col-2">
        <img src="https://placehold.it/200x200/f00" alt="Test">
      </div>
    </div>