Although a max width is set it is not being taken up on the smaller text - notice the widths of both examples are the same.
This snippet gives both the div and the h3 a position so that the widths are taken up and the div is set to have width fit-content (it will still obey the max-width).
The animation needs to take into account both the width of the container and the width of the text. It therefore uses left positioning and transition. For the shorter text they balance out so there is no movement. For the longer text the amount of movement is just the extra length of the text compared to the container.
.animated {
position: relative;
white-space: nowrap;
max-width: 200px;
overflow: hidden;
background: #0c0c0c;
display: inline-block;
width: fit-content;
position: relative;
}
.text-animated {
color: #fff;
animation: backAndForth 5s linear infinite;
display: inline-block;
position: relative;
}
@keyframes backAndForth {
0% {
transform: translateX(0);
left(0);
}
10% {
transform: translateX(0);
left: 0;
}
45% {
transform: translateX(calc(-100%));
left: 100%;
}
55% {
transform: translateX(calc(-100%));
left: 100%;
}
90% {
transform: translateX(0);
left: 0;
}
100% {
transform: translateX(0);
left: 0;
}
}
<div class="animated">
<h3 class="text-animated">
Some Short Text
</h3>
</div>
<span>Must be fixed</span>
<br><br><br>
<div class="animated">
<h3 class="text-animated">
Some Long And Bigger Text To Animate
</h3>
</div>
<span>Must be Animated to view all text</span>
UPDATE: a couple of additional requirements have been added (in the comments below).
The max-width needs to change from a fixed px width to be relative to container size. The snippet below demonstrates this by putting the divs in a container whose width depends on viewport size.
The text direction has changed from left to right to right to left. The settings for left and transform/translate therefore have to swap signs compared to tehe original code above:
.container {
width: 40vw;
position: relative;
}
.animated {
position: relative;
white-space: nowrap;
/* max-width: 200px; */
max-width: calc(100% - 5rem);
overflow: hidden;
background: #0c0c0c;
display: inline-block;
width: fit-content;
position: relative;
white-space: no-wrap;
direction: rtl;
}
.text-animated {
color: #fff;
animation: backAndForth 5s linear infinite;
display: inline-block;
position: relative;
direction: rtl;
}
@keyframes backAndForth {
0% {
transform: translateX(0);
left(0);
}
10% {
transform: translateX(0);
left: 0;
}
45% {
transform: translateX(calc(100%));
left: -100%;
}
55% {
transform: translateX(calc(100%));
left: -100%;
}
90% {
transform: translateX(0);
left: 0;
}
100% {
transform: translateX(0);
left: 0;
}
}
<div class="container">
<div class="animated">
<h3 class="text-animated">
Some Short Text
</h3>
</div>
<br><br><br>
<div class="animated">
<h3 class="text-animated">
Some Long And Bigger Text To Animate
</h3>
</div>
</div>