Today, a friend of mine asked me a question:

Text does not wrap, beyond the container, how to scroll display?

For example, in the image below, some list items have short text and some have long text.

The requirement is: you want the long part of the text to scroll through the animation.

My first reaction was that I couldn’t do it with pure CSS.

But then I thought hard for a while, and I did it!

There are some interesting CSS knowledge points that I would like to share here.

1. How to let the text overflow the container?

The work-break property is used to handle how text is wrapped, using the less common keep-all value, which means that line breaks can only be done at half-corner Spaces or hyphens. Because these two special characters are not in the text, the text overflows.

2. How do I make the width of an element depend on the content?

3. Get moving?

Here we use keyframe animation to make it scroll first. Key frames are defined as follows:

@keyframes move {
  0%{
    transform: translateX(0px);
  }
  100%{
    transform: translateX(100%); }}Copy the code

The specific effect is:

As you can see here, the reason we set the width of the element to the width of the text itself in step 2 is that we animate the element relative to its width.

For example, we want the end of the text to be aligned with the right side of the div content box:

Since we know the width of the parent element (100px in this case), we can easily do this using calc() :

@keyframes move {
  0%{
    transform: translateX(0px);
  }
  100%{
    transform: translateX(calc(-100% + 100px)); }}Copy the code

The parent element hides the overflow as follows:

4. How to keep short text still?

On the whole, the scrolling effect is realized, but the demand of digging friends is, long text scrolling, short text motionless.

Later, slap thigh: set the minimum width of P!

5. Finally, optimize the animation!

Now the effect is, how can I say, too annoying to scroll, so we can pause the animation for a moment before the scroll starts and ends:

@keyframes move {
  0%, 20%{
    transform: translateX(0px); Were 80% and 100%} {transform: translateX(calc(-100% + 100px)); }}Copy the code

The first 20 percent remained the same, as did the second 20 percent:

One more problem, here our animation time is 3s, we can set the time according to the length of the text. That is, longer text takes longer.

But here, I didn’t know what to do with CSS, tried it a few times, and finally gave up and used a little JS.

[...document.querySelectorAll('p')].forEach(p= > {
	p.style.setProperty('--duration', p.offsetWidth / 100 + 's');
})
Copy the code

Where –duration is a CSS variable (please Google it for those who are not familiar with it), the animation property of the P tag should also be changed accordingly:

animation: move var(--duration) linear infinite;
Copy the code

Finally, for the complete code and effects, see codepen. IO /laoyao/pen/… .


Thanks for reading!

🙏 🙏 🙏