CSS animate scrolling text using text-indent
Asked Answered
I

1

8

I have created an "Important Notice" bar where I want the text to scroll across the screen.

It is achieved by animating the text-indent which seemed to work well until I had text which was longer than the width of the screen.

Here's the HTML:

<div class="sitemessage">
    dfgh hgsl;k sfghjh fgdlj dflgh sg jls sdfhsdkjldfjksg sdfg ksjdfhg klsjdfhg lksjdfhg klsjdhg lksjdhfg sldkfjgh sdflgkjsdfglk jsdfg klsdfgl jksdfgl jksdfg ljsdfgkjl dafglkj adfgkl sdfgkjh sdfgkhl sdfg kjlsdfgk lsdfgk jl sdfgkl adfgkl adfgklj sdfgklhj sdfgkl jdfg kljafdg ljkdfg klsdfgkhjl sdfgk jlsdfgkhj dfgkhl adfgkj adfkljg a
</div>

And here's my CSS:

.sitemessage {
    width:100%;
    max-width: 960px;
    margin:auto;
    white-space: nowrap;
    overflow: hidden;
    text-indent: 965px;
    animation: floatText 15s infinite linear;
}

.sitemessage:hover {
    -webkit-animation-play-state: paused;
    -moz-animation-play-state: paused;
    -o-animation-play-state: paused;
    animation-play-state: paused;
}

@-webkit-keyframes floatText{
    from {
        text-indent: 100%;
    }

    to {
        text-indent: -100%;
    }
}

@media screen and (min-width: 960px) {
    @-webkit-keyframes floatText{
        from {
            text-indent: 960px;
        }

        to {
            text-indent: -100%;
        }
    }
}

The problem I have is that the length of the text in the .sitemessage container could be a lot more or a lot less than 100% of the screen width, so using text-indent of -100% won't really work.

Any ideas of something I can do without resorting to Javascript or adding to the HTML.

Ible answered 24/11, 2016 at 14:44 Comment(2)
a quick fiddle of the behavior: jsfiddle.net/r2u8LdktSurpass
Recreating <marquee>. in 2016, nice! developer.mozilla.org/en-US/docs/Web/HTML/Element/marqueeIlsa
T
17

You can try using transform instead of text-indent.

jsFiddle

.sitemessage {
  display: inline-block;
  white-space: nowrap;
  animation: floatText 15s infinite linear;
  padding-left: 100%; /*Initial offset*/
}
.sitemessage:hover {
  animation-play-state: paused;
}
@keyframes floatText {
  to {
    transform: translateX(-100%);
  }
}
<div class="sitemessage">
  START dfgh hgsl;k sfghjh fgdlj dflgh sg jls sdfhsdkjldfjksg sdfg ksjdfhg klsjdfhg lksjdfhg klsjdhg lksjdhfg sldkfjgh sdflgkjsdfglk jsdfg klsdfgl jksdfgl jksdfg ljsdfgkjl dafglkj adfgkl sdfgkjh END
</div>
Ternopol answered 24/11, 2016 at 15:11 Comment(2)
Close, but it's animating the text within the div that I need to do, rather than the whole div. I'm guessing I might need to add a bit of html to get this to work in my case, but that's not the end of the world.Ible
Most of the percentage values relative to the width of the container rather than width of the element itself, that's why transform works in this case.Ternopol

© 2022 - 2024 — McMap. All rights reserved.