Brady Dowling
Brady Dowling

Reputation: 5532

Text reveal using CSS animation and background color

I'm trying to do a text reveal CSS animation like this one. Using ::before and ::after seems like an overly complicated approach so I'm trying to do this using a linear-gradient background color, background position, or something else that could be simpler.

:root {
  --primary-rgba: rgba(17,184,106,1);
  --secondary-rgba: rgba(255,255,255,1);
}

@keyframes slidein {
  0% {
    background: transparent;
  }
  25% {
    background: linear-gradient(90deg, var(--secondary-rgba) 0%, var(--secondary-rgba) 50%, var(--primary-rgba) 50% var(--primary-rgba) 100%); 
  }
  50% {
    background: var(--secondary-hex);
  }
  75% {
    background: linear-gradient(90deg, var(--primary-rgba) 0%, var(--primary-rgba) 50%, var(--secondary-rgba) 50% var(--secondary-rgba) 100%); 
  }
  100%   {
    background: transparent;
  }
}

I even wondered if adding more frames to the animation would make it work the way I wanted to and tried hacking in a bunch of (repetative) frames. Still no luck.

After finding out that CSS transitions likely don't support gradients yet, I tried using background position to reveal text but with no success.

Are either of these approaches doable?

Upvotes: 1

Views: 2085

Answers (1)

Temani Afif
Temani Afif

Reputation: 272919

The only way to create a reveal using background is to consider multiple background layer where one of them is using background-clip:text which will allow you to also color the text using background and control its position.

Here is an example based on a previous answer. The trick is to have two layers that we animate the same then at the end we animate the top one to make its width 0 while keeping the other (text layer) at width 100%

body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #8ce2ea;
  margin:0;
}

.reveal-text {
  position: relative;
  font-size: 50px;
  color: transparent;
  background-image: 
    linear-gradient(#f2f98b, #f2f98b), 
    linear-gradient(#fff,#fff);
  -webkit-background-clip:
    padding-box,
    text;
  background-clip:
    padding-box,
    text;
  background-size: 0% 100%;
  background-repeat: no-repeat;
  background-position: left;
  animation: revealer-text 0.8s 1s forwards;
}

@keyframes revealer-text {
  0% {
    background-size: 0% 100%;
  }
  50% {
    background-size: 100% 100%;
    background-position: left;
  }
  51% {
    background-size: 100% 100%;
    background-position: right;
  }
  100% {
    background-size: 0% 100%,100% 100%;
    background-position: right;
  }
}
<h1 class="reveal-text">
  I'm here.
</h1>

This may not work in all the browser so if you want a more supported way using background you will need at least an extra element like I did here Clip-path alternatives for reveal text

Upvotes: 5

Related Questions