alexkodr
alexkodr

Reputation: 543

CSS Animation - text sliding left to right

I'm trying to get some text to slide in from left to right with a delay. It will be appearing from the middle of the page rather than off canvas. I can easy get it to work when the text slides in from off the page.

Doing from the middle of the screen is a little different and i'm missing something. The text appears on page load (when it should be hidden). I can easy do this using jQuery, but i'm sure it's more than possible to do using just css. Here's what i got so far

HTML:

<div class="slide-right">
  <h2>Text that will slide in from the left</h2>
</div>

CSS:

.slide-right {
   width: 100%;
   overflow: hidden;
   margin-left: 400px;
   max-width: 500px
}

.slide-right h2 {
   animation: 2s slide-right;
   animation-delay: 2s;
}

@keyframes slide-right {
    from {
       margin-left: -500px;
    }

    to {
       margin-left: 0%;
    }
 }

.slide-right {
  width: 100%;
  overflow: hidden;
  margin-left: 400px;
  max-width: 500px
}

.slide-right h2 {
  animation: 2s slide-right;
  animation-delay: 2s;
}

@keyframes slide-right {
  from {
    margin-left: -500px;
  }

  to {
    margin-left: 0%;
  }
}
<div class="slide-right">
  <h2>Text that will slide in from the left</h2>
</div>

Like this

Thanks

Upvotes: 6

Views: 60599

Answers (1)

Temani Afif
Temani Afif

Reputation: 272816

You can hide the text initially and rely on forwards to keep the last state

.slide-right {
  width: 100%;
  overflow: hidden;
  margin-left: 300px;
  max-width: 500px
}

.slide-right h2 {
  animation: 2s slide-right 2s forwards;
    transform:translateX(-100%);
}

@keyframes slide-right {
  to {
    transform:translateX(0);
  }
}
<div class="slide-right">
  <h2>Text that will slide in from the left</h2>
</div>

Upvotes: 11

Related Questions