Skip to content
Advertisement

CSS Shimmer effect with blocking JavaScript

I have a shimmer React component with the following CSS

background: #ebebeb;
background-image: linear-gradient(to right,  #ebebeb 0%, #c5c5c5 20%,  #ebebeb 40%,  #ebebeb 100%);

and the animation keyframe I apply to it is as follows:

{
    0%: { background-position: -468px 0 };
    100%: { background-position: 468px 0 };
}

My home page is quite heavy on mount. So the animation freezes for about a second or so. I read that animating transition is done off-thread https://www.phpied.com/css-animations-off-the-ui-thread/

Can anyone help me do my shimmer effect in a similar off-thread manner?

Advertisement

Answer

Use transform as suggested in the link. Here is an idea with pseudo element:

.box {
  background-image: linear-gradient(to right, #ebebeb calc(50% - 100px), #c5c5c5 50%, #ebebeb calc(50% + 100px));
  background-size:0;
  height: 200px;
  position:relative;
  overflow:hidden;
}
.box::before {
  content:"";
  position:absolute;
  top:0;
  right:0;
  width:calc(200% + 200px);
  bottom:0;
  background-image:inherit;
  animation:move 2s linear infinite; 
}
@keyframes move{
  to {
    transform:translateX(calc(50% + 100px));
  }
}
<div class="box">

</div>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement