Home > Enterprise >  How to apply the same background animation on multiple child elements?
How to apply the same background animation on multiple child elements?

Time:08-10

I would like to know what is the better approach to making several elements to use the same animated background, as shown in the picture above. For sure, it is possible to calculate the animated gradient independently for each element, but I would like to have a general solution since a number of children and their position could be different.

Explanation

<div class = 'parent'>
  <div class = 'child child-header'>Child 1</div>
  <div class = 'child child-column'>Child 2</div>
  <div class = 'child child-column'>Child 3</div>
  <div class = 'child child-column'>Child 4</div>
</div>

.parent {
  display: flex;
  flex-direction: column;
  flex-flow: row wrap;
  justify-content: space-around;
}

.child {
  display: flex;
  background-color: #d8d8d8;
  background-image: linear-gradient(90deg,#d8d8d8,#bdbdbd,#d8d8d8);
  animation: skeleton-shimmer 2.5s ease-in-out infinite;
  background-size: 200px 100%;
  background-repeat: no-repeat;
}

.child-header {
  width: 100%;
}

.child-column {
  width: 33%;
}

@keyframes skeleton-shimmer {
  0% {
    background-position: -200px 0;
  }
  100% {
    background-position: calc(200px   100%) 0;
  }
}

https://jsfiddle.net/0zarfbgw/

What I would like to achieve here is to make all children use a single animation effect (children could have different positions).

CodePudding user response:

You could apply the moving background to each of the children's before pseudo element - that pseudo element covering the whole parent.

This snippet puts a clip path on each of the children so the 'excess' background on the pseudo element isn't seen. For the purposes of demonstration it also spaces them out a bit and puts a black background color on the parent so the difference in the two backgrounds can be seen.

.parent {
  display: flex;
  flex-direction: column;
  flex-flow: row wrap;
  justify-content: space-around;
  gap: 10vmin;
  position: relative;
  background-color: black;
}

.child {
  clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%);
}

.child::before {
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: -1;
  background-color: #d8d8d8;
  background-image: linear-gradient(90deg, #d8d8d8, #bdbdbd, #d8d8d8);
  animation: skeleton-shimmer 2.5s ease-in-out infinite;
  background-size: 200px 100%;
  background-repeat: no-repeat;
}

.child-header {
  width: 100%;
}

.child-column {
  width: 33%;
}

@keyframes skeleton-shimmer {
  0% {
    background-position: -200px 0;
  }
  100% {
    background-position: calc(200px   100%) 0;
  }
}
<div class='parent'>
  <div class='child child-header'>Child 1</div>
  <div class='child child-column'>Child 2</div>
  <div class='child child-column'>Child 3</div>
  <div class='child child-column'>Child 4</div>
</div>

  • Related