Deep Tech Point
first stop in your tech adventure

CSS animations: How to make the text slide across the browser window?

September 4, 2021 | CSS

This is one of the simplest animations there are. We will animate the <p> element and will make that the text inside the element slide in the user’s view from the left edge of the browser window to the right.

The animation will look like this:

See the Pen
slide-left-to-right
by Tanja (@tanjatod)
on CodePen.

Now, let’s take a look at the HTML part – we will animate the <p> element and we named the class of div that encapsulates the animated element “slide-left-to-right”

<div class="slide-left-to-right">
  <p>Text that slides from left to right</p>
</div>

Next, let’s peek at the CSS and what it means:

sliding-text {
  width: 100%;
  overflow: hidden;
}

.sliding-text p {
  animation: 3s slide-left-to-right 1s forwards;
    transform:translateX(-100%);
}

@keyframes slide-left-to-right {
  to {
    transform:translateX(0%);
  }
}

We named the class “sliding-text”.
We defined the width to be 100% which means that the element’s total width will be 100% of its containing block plus any horizontal margin, padding and border.
We’ve set overflow: hidden on a container because animations like these cause the page to become wider than the browser window. We wanted to avoid that.

Next, we declared that we wanted to style the <p> element. We used the animation shorthand and said that:

If you would like to know more about animation shorthand property, you should look at this complete guide to CSS animation with all 8 animation subproperties explained through examples.

What about transform:translateX(0) and transform:translateX(-100%);?
The translateX() CSS function repositions an element horizontally on the 2D plane.
The goal of this function was to hide the text out of sight, therefore transform:translateX(-100%); and and place it back on the screen, therefore transform:translateX(0%);. We could have used length units, and, for example, if we wanted the text to slide in and stay positioned on the second half of the screen, we would have used transform:translateX(50%);
We didn’t use from @keyframes at-rule because we hid the text, so there was no need to define the starting position.