Search code examples
csslinear-gradientsbackground-positioncss-gradients

Setting linear-gradient offset as percentage without background-size


This looks simple and must be asked before, but I cannot find the question.

I have the following animation:

@keyframes bar-animation
{
    to
    {
        background-position-y: 20px;
    }
}

.bar
{
    width: 200px;
    height: 20px;
    background: linear-gradient(red, blue, red);
    animation: bar-animation 1s ease-in infinite;
}
<div class="bar"></div>

It works fine except the fact I should repeat 20px twice: when setting height of the div element and when setting the vertical offset (it must be divisible by the height to make the animation smooth).

Is there a way to make the class applicable to containers with different heights? Setting the offset as percentage requires background-size that I can't specify either.


Solution

  • Use a repeating linear gradient to define your gradient. Define a height equal to 200% then you can easily slide it from top to bottom (or the opposite)

    @keyframes bar-animation {
      to {
        background-position: top;
      }
    }
    
    .bar {
      height: 40px;
      background: 
        repeating-linear-gradient(red 0, blue, red 50%) 
        bottom/100% 200%;
      animation: bar-animation 1s ease-in infinite;
    }
    <div class="bar"></div>