4

В качестве основного фонового изображения используется следующий линейный градиент:

html, body, svg {margin: 0; padding: 0; width: 100%; height: 100vh;}
<svg id="svg">
<defs>
<linearGradient id="gradient">
<stop offset="0" stop-color="brown"/>
<stop offset="2" stop-color="chocolate"/>
</linearGradient>
</defs>
<rect x="0" y="0" width="100%" height="100vh" fill="url(#gradient)"/>

Как мы знаем, градиент — это плавный переход от одного цвета к другому. Самих цветов и переходов между ними может быть несколько. В данном примере используется только два цвета — коричневый и шоколадный.

Мне необходимо реализовать анимацию этого градиента. Нужно пустить разделяющую вертикальную белую полосу, которая будет двигаться слева направо, и затем в обратном направлении. Таким образом, удаляясь от одного края, эта полоса будет как-бы тянуть градиент за собой, тем самым заполняя основной фон плавным переходом от одного цвета к белому. Затем в обратном направлении, заполняя основной фон плавным переходом от другого цвета к белому.

Градиент

Сценарий анимации:

  1. Вертикальная белая полоса двигается слева направо, заполняя основной фон плавным переходом от коричневого к белому;
  2. Вертикальная белая полоса двигается справа налево, заполняя основной фон плавным переходом от шоколадного к белому;
  3. Анимация зацикливается.

Это самый простой сценарий такой анимации. Однако, если это возможно, то мне хотелось бы этот сценарий немного усложнить:

  1. Вертикальная белая полоса двигается слева направо, заполняя основной фон плавным переходом от коричневого к белому. За время этой анимации основное фоновое изображение трансформируется в виде вращения на 360o по часовой стрелке;
  2. Вертикальная белая полоса двигается справа налево, заполняя основной фон плавным переходом от шоколадного к белому. За время этой анимации основное фоновое изображение трансформируется в виде вращения на 360o против часовой стрелки;
  3. Анимация зацикливается.

Реализовать такую анимацию предлагается любыми средствами, указанными в метках вопроса, а именно — как CSS, SMIL SVG, так и с помощью JavaScript (а это может быть и Canvas - HTML элемент, использующий язык программирования - JavaScript).

5 ответов 5

3

Во всех примерах ниже gradientUnits="objectBoundingBox" это дефолтное значение, поэтому, если не указано явно gradientUnits="userSpaceOnUse" значения атрибутов будут либо в процентах, либо соответственно от 0 до 1 Что означает, что градиент будет действовать на всю фигуру.

Анимировать будем значения атрибутов градиента x1, x2, y1, y2

#1. Перемещение белой полосы с протяжкой цвета слева-направо

<svg width="300" height="300" version="1.1" xmlns="http://www.w3.org/2000/svg">
  <defs>
      <linearGradient id="Gradient" x1="0" x2="0" y1="0" y2="0">
         <animate attributeName="x2" values="0;1;1;0;0" keyTimes="0;.25;.5;.75;1"  dur="2s" repeatCount="indefinite" />  
         <stop offset="0%" stop-color="brown"/>
        <stop offset="50%" stop-color="white"/>
        <stop offset="100%" stop-color="chocolate"/>
      </linearGradient>
  </defs>
  <rect x="10" y="10" width="240" height="240" rx="25" fill="url(#Gradient)"/>
  
</svg>

#2. Вращение белой полосы

<svg width="300" height="300" version="1.1" xmlns="http://www.w3.org/2000/svg">
  <defs>
      <linearGradient id="Gradient" x1="0" x2="0" y1="0" y2="1">
        <animate attributeName="x1" values="0;0;1;1;0" keyTimes="0;.25;.5;.75;1" dur="1s" repeatCount="indefinite" />
        <animate attributeName="y1" values="0;1;1;0;0" keyTimes="0;.25;.5;.75;1" dur="1s" repeatCount="indefinite" />
        <animate attributeName="x2" values="1;1;0;0;1" keyTimes="0;.25;.5;.75;1" dur="1s" repeatCount="indefinite" />
        <animate attributeName="y2" values="1;0;0;1;1" keyTimes="0;.25;.5;.75;1" dur="1s" repeatCount="indefinite" />
        <stop offset="0%" stop-color="brown"/>
        <stop offset="50%" stop-color="white"/>
        <stop offset="100%" stop-color="chocolate"/>
      </linearGradient>
  </defs>
  <rect x="10" y="10" width="240" height="240" rx="25" fill="url(#Gradient)"/>
  
</svg>

#3. Вращение белой полосы с другими цветами внутри звезды

<svg xmlns="http://www.w3.org/2000/svg" width="475.07" height="475.07" viewBox="0 0 475.075 475.075" fill="#FFF">
<defs>
      <linearGradient id="Gradient" x1="0" x2="0" y1="0" y2="1">
        <animate attributeName="x1" values="0;0;1;1;0" keyTimes="0;.25;.5;.75;1" dur="1.5s" repeatCount="indefinite" />
        <animate attributeName="y1" values="0;1;1;0;0" keyTimes="0;.25;.5;.75;1" dur="1.5s" repeatCount="indefinite" />
        <animate attributeName="x2" values="1;1;0;0;1" keyTimes="0;.25;.5;.75;1" dur="1.5s" repeatCount="indefinite" />
        <animate attributeName="y2" values="1;0;0;1;1" keyTimes="0;.25;.5;.75;1" dur="1.5s" repeatCount="indefinite" />
        <stop offset="0%" stop-color="red"/>
        <stop offset="50%" stop-color="white"/>
        <stop offset="100%" stop-color="blue"/>
      </linearGradient>
  </defs>
<path fill="url(#Gradient)"  d="M324.63 288.5l20.55 120.2-107.63-56.82L129.6 408.7l20.86-120.2-87.37-84.8L183.57 186l53.95-109.06L291.5 186 412 203.7l-87.38 84.8z"/>
</svg>

#4. Двойная звезда вращение градиента на нижнем контуре

<svg xmlns="http://www.w3.org/2000/svg" width="475.07" height="475.07" viewBox="0 0 475.075 475.075" fill="#FFF">
<defs>
<linearGradient id="Lg" x1="0" x2="0" y1="0" y2="1">
        <animate attributeName="x1" values="0;0;1;1;0" keyTimes="0;.25;.5;.75;1" dur="1s" repeatCount="indefinite" />
        <animate attributeName="y1" values="0;1;1;0;0" keyTimes="0;.25;.5;.75;1" dur="1s" repeatCount="indefinite" />
        <animate attributeName="x2" values="1;1;0;0;1" keyTimes="0;.25;.5;.75;1" dur="1s" repeatCount="indefinite" />
        <animate attributeName="y2" values="1;0;0;1;1" keyTimes="0;.25;.5;.75;1" dur="1s" repeatCount="indefinite" />
        <stop offset="0%" stop-color="brown"/>
        <stop offset="50%" stop-color="white"/>
        <stop offset="100%" stop-color="chocolate"/>
      </linearGradient>
</defs>   
<path  fill="url(#Lg)" stroke="brown"   stroke-width="1" d="M475.07 186.57c0-7.04-5.32-11.42-16-13.13l-143.3-20.84-64.24-129.9c-3.62-7.8-8.28-11.7-14-11.7-5.7 0-10.36 3.9-13.98 11.7L159.3 152.6 16 173.44c-10.67 1.7-16 6.1-16 13.13 0 4 2.38 8.57 7.14 13.7l103.92 101.08L86.5 444.1c-.37 2.66-.56 4.57-.56 5.7 0 4 1 7.38 3 10.14 2 2.77 5 4.15 9 4.15 3.42 0 7.22-1.15 11.4-3.44l128.2-67.38 128.2 67.38c4 2.28 7.8 3.43 11.4 3.43 7.82 0 11.72-4.76 11.72-14.28 0-2.48-.1-4.38-.3-5.72l-24.54-142.74L467.66 200.3c4.94-4.97 7.4-9.54 7.4-13.73z"/>
    
    <path fill="brown" stroke="shocolate" stroke-width="2" d="M324.63 288.5l20.55 120.2-107.63-56.82L129.6 408.7l20.86-120.2-87.37-84.8L183.57 186l53.95-109.06L291.5 186 412 203.7l-87.38 84.8z"/>
</svg>

#5. Двойная звезда разные, вращающиеся градиенты на разные контуры

<svg xmlns="http://www.w3.org/2000/svg" width="475.07" height="475.07" viewBox="0 0 475.075 475.075" fill="#FFF">
<defs>
<linearGradient id="Lg1" x1="0" x2="0" y1="0" y2="1">
        <animate attributeName="x1" values="0;0;1;1;0" keyTimes="0;.25;.5;.75;1" dur="1s" repeatCount="indefinite" />
        <animate attributeName="y1" values="0;1;1;0;0" keyTimes="0;.25;.5;.75;1" dur="1s" repeatCount="indefinite" />
        <animate attributeName="x2" values="1;1;0;0;1" keyTimes="0;.25;.5;.75;1" dur="2s" repeatCount="indefinite" />
        <animate attributeName="y2" values="1;0;0;1;1" keyTimes="0;.25;.5;.75;1" dur="2s" repeatCount="indefinite" />
        <stop offset="0%" stop-color="brown"/>
        <stop offset="50%" stop-color="white"/>
        <stop offset="100%" stop-color="chocolate"/>
      </linearGradient> 
     <linearGradient id="Lg2" x1="0" x2="0" y1="0" y2="1">
        <animate attributeName="x1" values="0;0;1;1;0" keyTimes="0;.25;.5;.75;1" dur="1s" repeatCount="indefinite" />
        <animate attributeName="y1" values="0;1;1;0;0" keyTimes="0;.25;.5;.75;1" dur="1s" repeatCount="indefinite" />
        <animate attributeName="x2" values="1;1;0;0;1" keyTimes="0;.25;.5;.75;1" dur="1s" repeatCount="indefinite" />
        <animate attributeName="y2" values="1;0;0;1;1" keyTimes="0;.25;.5;.75;1" dur="1s" repeatCount="indefinite" />
        <stop offset="0%" stop-color="brown"/>
        <stop offset="50%" stop-color="white"/>
        <stop offset="100%" stop-color="crimson"/>
      </linearGradient> 
</defs>   
<path  fill="url(#Lg1)" stroke="black"  stroke-width="1" d="M475.07 186.57c0-7.04-5.32-11.42-16-13.13l-143.3-20.84-64.24-129.9c-3.62-7.8-8.28-11.7-14-11.7-5.7 0-10.36 3.9-13.98 11.7L159.3 152.6 16 173.44c-10.67 1.7-16 6.1-16 13.13 0 4 2.38 8.57 7.14 13.7l103.92 101.08L86.5 444.1c-.37 2.66-.56 4.57-.56 5.7 0 4 1 7.38 3 10.14 2 2.77 5 4.15 9 4.15 3.42 0 7.22-1.15 11.4-3.44l128.2-67.38 128.2 67.38c4 2.28 7.8 3.43 11.4 3.43 7.82 0 11.72-4.76 11.72-14.28 0-2.48-.1-4.38-.3-5.72l-24.54-142.74L467.66 200.3c4.94-4.97 7.4-9.54 7.4-13.73z"/>
    
    <path fill="url(#Lg2)" stroke="black" d="M324.63 288.5l20.55 120.2-107.63-56.82L129.6 408.7l20.86-120.2-87.37-84.8L183.57 186l53.95-109.06L291.5 186 412 203.7l-87.38 84.8z"/>
</svg>

Другие примеры с протяжкой цвета за бегущей полосой

#1. Горизонтально слева-направо и обратно

<style>
.crc1 {
  fill: url('#Lg');
}
</style>
<svg class="the-svg" width="100%" height="100%" viewBox="-20 -20 200 200">
  <circle class="crc1" cx="50" cy="50" r="50"  />
  <defs>
    <linearGradient id="Lg" x1="0" x2="0" y1="0" y2="0" gradientUnits="userSpaceOnUse">
      <stop offset="20%" stop-color="#24bed2"/>
      <stop offset="90%" stop-color="#FF00AE"/>
    <animate attributeName="x1" dur="4s" values="0;200;200;0" repeatCount="indefinite" />
    </linearGradient>
  </defs>
</svg>

#2. Вертикальная протяжка цвета

<style>
.crc1 {
  fill: url('#Lg');
}
</style>
<svg class="the-svg" width="100%" height="100%" viewBox="-20 -20 200 200">
  <circle class="crc1" cx="50" cy="50" r="50"  />
  <defs>
    <linearGradient id="Lg" x1="0" x2="0" y1="0" y2="0" gradientUnits="userSpaceOnUse">
      <stop offset="20%" stop-color="#24bed2"/>
      <stop offset="90%" stop-color="#FF00AE"/>
    <animate attributeName="y1" dur="4s" values="0;200;200;0" repeatCount="indefinite" />
    </linearGradient>
  </defs>
</svg>

#3. Под углом

<style>
.crc1 {
  fill: url('#Lg');
}
</style>
<svg class="the-svg" width="100%" height="100%" viewBox="-10 -10 200 200">
  <circle class="crc1" cx="50" cy="50" r="50"  />
  <defs>
    <linearGradient id="Lg" x1="0" x2="0" y1="0" y2="0" gradientUnits="userSpaceOnUse">
      <stop offset="10%" stop-color="#24bed2"/>
      <stop offset="90%" stop-color="#FF00AE"/>
      <animate attributeName="x1" dur="5s" values="0;200;200;0" repeatCount="indefinite" />
      <animate attributeName="y1" dur="5s" values="0;200;200;0" repeatCount="indefinite" />
    </linearGradient>
  </defs>
</svg>

#4.Смена пары цветов на другую пару при наведении курсора (по моему выглядит симпатично)

<style>
.crc1 {
  fill: url('#Lg');
}
 .crc1 ~ defs stop {
  transition: 3s;
}

.crc1 ~ defs stop:first-child {
  stop-color: #24bed2;
}
.crc1:hover ~ defs stop:last-child {
  stop-color: #F4FFAF;
} 
</style>
<svg class="the-svg" width="200px" height="200" viewBox="-10 -10 120 120">
  <circle class="crc1" cx="50" cy="50" r="50"  stroke="#F4FFAF"/>
  <defs>
    <linearGradient id="Lg" x1="0" x2="0" y1="90" y2="0" gradientUnits="userSpaceOnUse">
      <stop offset="2%" stop-color="#2C2C2C"/>
      <stop offset="50%" stop-color="#2C2C2C"/>
    </linearGradient>
  </defs>
</svg>

[BONUS]

Вращение трех колец с градиентной анимацией

.container {
width:50%;
height:50%;
}

svg {
background:black;
}

#path1 {
fill:url(#gradl);
stroke:none;
fill-opacity:1;
}
#path2 {
fill:url(#grad2);
stroke:none;
fill-opacity:0.8;
}
#crc1 {
stroke:none;
fill:black;
}
#txt1 {
fill:url(#grad2);

}
<div class="container">
 
<svg id="svg1" xmlns="http://www.w3.org/2000/svg"  xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"  viewBox="0 0 300 300" > 
<defs>
        <linearGradient id="gradl" gradientUnits="objectBoundingBox" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stop-color="dodgerblue"> 
             <animate attributeName="stop-color" dur="1.5s" values="dodgerblue;yellow;dodgerblue" repeatCount="indefinite" restart="whenNotActive" />   
             </stop>             
            <stop offset="100%" stop-color="yellow">
           <animate attributeName="stop-color" dur="1.5s" values="yellow;dodgerblue;yellow" repeatCount="indefinite"  restart="whenNotActive" />    
             </stop>                        
            
        </linearGradient> 
        <linearGradient id="grad2" gradientUnits="objectBoundingBox" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stop-color="lime">
              <animate attributeName="stop-color" dur="1.5s" values="lime;purple;lime" repeatCount="indefinite" restart="whenNotActive" />  
             </stop>                
            <stop offset="100%" stop-color="purple">
           <animate attributeName="stop-color" dur="1.5s" values="purple;lime;purple" repeatCount="indefinite" restart="whenNotActive"  />  
             </stop>                
        </linearGradient>
    
        </defs>
<path id="path1" d="M71.9 78.4C90.8 58.1 122.9 50.7 150.6 51.5c26.2 0.7 54.9 10.5 72.8 29.7 16.9 18.1 22.9 45.8 23.4 70.6 0.5 25.1-3.2 54.4-20.7 72.4-18.5 19.1-49.4 24.5-76 24.3-25.4-0.2-54.4-6.3-72.4-24.3C59.5 205.8 53.9 176.5 53 150.8 52.2 125.9 55 96.7 71.9 78.4Z" > 
 <animateTransform attributeName="transform" type="rotate" values="0 150 150;360 150 150" begin="svg1.click" dur="20s" restart="whenNotActive" /> 
</path>

<path id="path2" transform="rotate(45 150 150)" d="M71.9 78.4C90.8 58.1 122.9 50.7 150.6 51.5c26.2 0.7 54.9 10.5 72.8 29.7 16.9 18.1 22.9 45.8 23.4 70.6 0.5 25.1-3.2 54.4-20.7 72.4-18.5 19.1-49.4 24.5-76 24.3-25.4-0.2-54.4-6.3-72.4-24.3C59.5 205.8 53.9 176.5 53 150.8 52.2 125.9 55 96.7 71.9 78.4Z" >
 <animateTransform attributeName="transform" type="rotate" values="360 148 148;0 148 148" begin="svg1.click" dur="20s" restart="whenNotActive" />  
</path>
<circle id="crc1" cx="150" cy="150" r="90" /> 
 <text id="txt1" x="80" y="160" font-size="36" font-weight="700" > Click me </text>
</svg>  
</div>

0
3

CSS.registerProperty && CSS.registerProperty({
  name: '--linepos',
  syntax: '<length-percentage>',
  inherits: true,
  initialValue: 0,
});
html, body, main {
  height: 100%;
  margin: 0;
}

main {
  --linepos: 50%;
  background: linear-gradient(to right, chocolate, white 50%, brown);
  background: linear-gradient(to right, chocolate, white var(--linepos), brown);
  animation: linepos 3s alternate infinite;
}

@keyframes linepos {
  from { --linepos: 0% }
  to { --linepos: 100% }
}

@property --linepos {
  syntax: '<length-percentage>';
  inherits: true;
  initial-value: 0;
}
<main></main>

С поворотом как-то так, но пока не получилось:

CSS.registerProperty && CSS.registerProperty({
  name: '--linepos',
  syntax: '<length-percentage>',
  inherits: true,
  initialValue: 0,
});

CSS.registerProperty && CSS.registerProperty({
  name: '--slope',
  syntax: '<angle>',
  inherits: true,
  initialValue: "0turn",
});
html, body, main {
  height: 100%;
  margin: 0;
}

main {
  --linepos: 50%;
  --slope: .25turn;
  background: linear-gradient(to right, chocolate, white 50%, brown);
  background: linear-gradient(var(--slope), chocolate, white var(--linepos), brown);
  animation: anim 10s infinite;
}

@keyframes anim {
  from   { --linepos:   0%;   --slope:  .25turn; }
  50%    { --linepos: 100%;   --slope:  .75turn; }
  to     { --linepos:   0%;   --slope: 1.25turn; }
}

@property --linepos {
  syntax: '<length-percentage>';
  inherits: true;
  initial-value: 0;
}

@property --slope {
  syntax: '<angle>';
  inherits: true;
  initial-value: 0turn;
}
<main></main>

4
  • @Sevastopol', я бы сказал, что у нас совершенно разные решения) Я тут попробовал поворот приделать - чую, что надо подумать над математикой, но пока фигня. И у анимации переменных поддержка пока так себе.
    – Qwertiy
    8 апр 2021 в 18:10
  • @Sevastopol', ну тут косяк в том, что когда переворачивается точка отсчёта, сдвиг начинает считаться справа, а не слева, а значит в правую половину центр белой полосы никогда не попадает. Но ещё мне кажется, что с отсчётом процентов при наклоне тоже что-то было не то, хотя не уверен. Кажется, надо где-то что-то прибавить в анимации, но я пока не понял, что и где. Хотя да, смотрится интересно.
    – Qwertiy
    8 апр 2021 в 18:18
  • @Sevastopol', @keyframes anim { 0% { --linepos: 0%; --slope: .25turn; } 25% { --linepos: 50%; --slope: .50turn; } 50% { --linepos: 0%; --slope: .75turn; } 75% { --linepos: 50%; --slope: 1.00turn; } 100% { --linepos: 0%; --slope: 1.25turn; } } - так правдоподобнее, но задержка на горизонтальном положении явно не в тему.
    – Qwertiy
    8 апр 2021 в 18:35
  • 1
    @Sevastopol', ой, ёёёёё.. Я даже не заметил, что у меня его нет. Да, гораздо лучше, только всё равно визуально видно моментальную смену точки вращения.
    – Qwertiy
    8 апр 2021 в 19:28
2

Предлагаю рассмотреть вариант анимации по первому (упрощённому) сценарию с помощью технологии SMIL SVG.

Чтобы реализовать такую анимацию, нам необходимо добавить еще один цвет для градиента — белый:

<stop stop-color="white">

Добавляем анимацию, и указываем для нее необходимые атрибуты и значения:

attributeName=offset — этот параметр отвечает за границу области градиента;

dur=5s — длительность анимации;

values=0;1;0 — список значений, который будет определять порядок следования анимации;

repeatCount=indefinite — количество раз выполнения анимации. Значение indefinite указывает на то, что анимация будет повторяться бесконечно.

Всё это заключаем в тег <animate>:

<animate attributeName="offset" dur="5s" values="0;1;0" repeatCount="indefinite" />

html, body, svg {margin: 0; padding: 0; width: 100%; height: 100vh;}
<svg id="svg">
<defs>
<linearGradient id="gradient">
<stop offset="0" stop-color="brown"/>
<stop stop-color="white">
<animate attributeName="offset" dur="5s" values="0;1;0" repeatCount="indefinite" /></stop>
<stop offset="1" stop-color="chocolate"/>
</linearGradient>
</defs>
<rect x="0" y="0" width="100%" height="100vh" fill="url(#gradient)"/>

Повернем угол наклона градиентной линии на 90o

html, body, svg {margin: 0; padding: 0; width: 100%; height: 100vh;}
<svg id="svg">
<defs>
<linearGradient id="gradient" gradientTransform="rotate(90 0 0)">
<stop offset="0" stop-color="brown"/>
<stop stop-color="white">
<animate attributeName="offset" dur="5s" values="0;1;0" repeatCount="indefinite" /></stop>
<stop offset="1" stop-color="chocolate"/>
</linearGradient>
</defs>
<rect x="0" y="0" width="100%" height="100vh" fill="url(#gradient)"/>

2

CSS решение

Белая полоса и её анимация появляются при наведении курсора

  • Белая полоса формируется с помощью linear-gradient
 background:linear-gradient(to bottom,brown, #fff 30px, chocolate 60px)
   no-repeat 0 -100px /100% 10%, chocolate;
  • Анимация движения белой полосы реализовано с помощью изменения background-position

Горизонтальная анимация

body{
  margin:0;
  padding:0;
}
.box{
  width:100vw;
  height:50vh;
  background-color:chocolate;
  min-height:25vh;
 
}
.box:hover{
  background:linear-gradient(to right,brown, #fff 30px, chocolate 60px) no-repeat -100px 0/100px 100%, chocolate;
 animation:draw 3s ease-in-out alternate infinite; 
}
@keyframes draw{
  from{
    background-position:-35px 0;
  }
  to{
    background-position:105% 0;
  }
}
<div class="box"></div>

Вертикальная анимация

body{
  margin:0;
  padding:0;
}
.box{
  width:15vw;
  height:100vh;
  background-color:chocolate;
  min-height:50vh;
  transition:all .4s ease-in-out;
}
.box:hover{
  background:linear-gradient(to bottom,brown, #fff 30px, chocolate 60px) no-repeat 0 -100px /100% 10%, chocolate;
  animation:draw 4s ease-in-out alternate infinite;
}
@keyframes draw{
  from{
    background-position:5% 0%;
  }
  to{
    background-position: 5% 105%;
  }
}
<div class="box"></div>

0
2

Предлагаю рассмотреть вариант анимации по первому (упрощённому) сценарию с помощью технологии CSS

Такую анимацию в данном варианте мы можем реализовать с помощью псевдоэлементов ::before и ::after к элементу <body>, а также правил @keyframes, установив общие ключевые кадры, включая в них свойства ширины width (для первого варианта) или высоты height (для второго варианта).

html, body {margin: 0; padding: 0; width: 100%; height: 100vh; position: relative;}

body::before, body::after {
  content: ""; display: block; height: 100vh; width: 100%;
  position: absolute; top: 0; bottom: 0;
}

body::before {
  left: 0; background: linear-gradient(90deg, brown, white);
  animation: before 5s linear infinite;
}

body::after {
  right: 0; background: linear-gradient(90deg, white, chocolate);
  animation: after 5s linear infinite;
}

@keyframes before {
  0% {width: 0;}
  50% {width: 100%;}
  100% {width: 0;}
}

@keyframes after {
  0% {width: 100%;}
  50% {width: 0;}
  100% {width: 100%;}
}

Повернем угол наклона градиентной линии на 90o

html, body {margin: 0; padding: 0; width: 100%; height: 100vh; position: relative;}

body::before, body::after {
  content: ""; display: block; height: 100vh; width: 100%;
  position: absolute; left: 0; right: 0;
}

body::before {
  top: 0; background: linear-gradient(180deg, brown, white);
  animation: before 5s linear infinite;
}

body::after {
  bottom: 0; background: linear-gradient(180deg, white, chocolate);
  animation: after 5s linear infinite;
}

@keyframes before {
  0% {height: 0;}
  50% {height: 100%;}
  100% {height: 0;}
}

@keyframes after {
  0% {height: 100%;}
  50% {height: 0;}
  100% {height: 100%;}
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.