Creating a running text (marquee) with CSS is a simple and efficient way to make

I encountered a significant challenge while delving into CSS animation.

My goal is to create a "transform: translate" animation that displays text overflowing the content width as depicted in the image below. https://i.stack.imgur.com/sRF6C.png
See it in action (Youtube video link)

var div1 = document.getElementById("div1");
var cont = document.getElementById("content");
var inf = document.getElementById("inf");

inf.innerHTML = "<p> Does the text inside h1 cut off? : " + (cont.offsetWidth < cont.scrollWidth) +
  "<br><b>Length of text overflow</b>: " + (cont.offsetWidth - cont.scrollWidth) +
  "<br> h1 width: " + (cont.offsetWidth) + ", h1's text length: " + (cont.scrollWidth) + "</p>";


div1.style.backgroundColor = "#A13DAF";
cont.style.webkitAnimationName = "moving";
cont.style.animationName = "moving";

cont.style.animationDuration = "3s";
cont.style.webkitAnimationDuration = "3s";

cont.style.animationTimingFunction = "linear";
cont.style.webkitAnimationTimingFunction = "linear";
#div1 {
  margin: 10px;
  width: 300px;
  background: rgb(40, 40, 40);
  white-space: nowrap;
  overflow: hidden;
}

#content {
  color: white;
  width: 100%;
}

@keyframes moving {
  0% {
    transform: none;
    -webkit-transform: none;
  }
  65% {
    transform: translate( calc(#content.scrollWidth - #content.offsetWidth), 0);
    -webkit-transform: translate( calc(#content.scrollWidth - #content.offsetWidth), 0);
    transform: translate( -668px, 0);
    -webkit-transform: translate( -668px, 0);
  }
  100% {
    transform: translate( -668px, 0);
    -webkit-transform: translate( -668px, 0);
  }
}
<div id="div1">
  <h1 id="content">
    The only thing that matters now is everything You think of me
  </h1>
</div>
<div id="inf"></div>

Inspired by the above code,
I am aiming to devise a mechanism where the text within the content (h1) shifts left precisely by the amount of overflow. Yet, I'm struggling to reference values of content directly in CSS.

Does a method exist to adjust a CSS value based on another element's specific value without relying on JavaScript??

I am striving to minimize reliance on Javascript for altering keyframes despite its potential complexity.

Your guidance is greatly appreciated.

Answer №1

One suggestion is to animate both the transform property and the margin-left property simultaneously, ensuring that the animation ends precisely at the end of the text:

.marquee {
  position: relative;
  overflow: hidden;
  background: rgb(161, 61, 175);
  color: #fff;
}

.marquee span {
  display: inline-block;
  min-width: 100%; /* prevent shorter text from animating beyond right edge */
  white-space: nowrap;
  font-size: 2.5em;
  animation: marquee 4s ease-in-out forwards;
}

@keyframes marquee {
  from {transform: translateX(0);     margin-left: 0;}
  to   {transform: translateX(-100%); margin-left: 100%; }
}
<h1 class="marquee">
  <span>Focus on what truly matters--everything you believe about me.</span>
</h1>

<p class="marquee">
  <span>Be cautious with short texts!</span>
</p>

Answer №2

Presented here is an alternative concept that relies solely on the transform property for animation:

.marquee {
  overflow: hidden;
  background: rgb(161, 61, 175);
  color: #fff;
}

.marquee > span {
 display:block;
 animation: marquee 4s ease-in-out;
 transform: translateX(100%);
}
.marquee > * > span {
 display: inline-block;
 min-width: 100%;
 white-space: nowrap;
 font-size: 2.5em;
 animation:inherit;
 transform: translateX(-100%);
}

@keyframes marquee {
 from {
   transform: translateX(0);
 }
}
<h1 class="marquee">
  <span>
    <span>The only thing that matters now is everything You think of me</span>
  </span>
</h1>

<h1 class="marquee">
  <span>
    <span>The only thing that matters now is everything</span>
  </span>
</h1>

<p class="marquee">
  <span>
    <span>Beware of short texts!</span>
  </span>
</p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript Processing Multiple Input Values to Produce an Output

Hello, I am working on creating a stamp script that will allow users to enter their name and address into three fields. Later, these fields will be displayed in the stamp edition. Currently, I have set up 3 input fields where users can input their data. He ...

Anticipate that the function parameter will correspond to a key within an object containing variable properties

As I develop a multi-language application, my goal is to create a strict and simple typing system. The code that I am currently using is as follows: //=== Inside my Hook: ===// interface ITranslation { [key:string]:[string, string] } const useTranslato ...

I am currently attempting to create a JavaScript function that searches for the <td> elements within an HTML table. However, the function fails to work properly when there are <th></th> tags included

UPDATE: Scratch that, I managed to solve my issue by creating a separate table for the header to contain all of my <th> tags I am working with an HTML table and I would like to add a search bar to filter through the content since it is quite large. ...

What is the method to allocate the smallest available number that has not yet been assigned?

As I'm dynamically generating elements and adding them to the page, each element needs a unique numerical id. However, due to non-linear removal of elements, there can be gaps in the assigned ids. For example... In one scenario: 1, 3, 4, 5, 16, 22. ...

The electron program is unable to locate the package.json module

I am new to electron and attempting to run an express app for the first time. However, I encountered this error: Need assistance updating code Error: Cannot find module 'C:\package.json' at Module._resolveFilename (module.js:440:15) ...

Running Javascript based on the output of PHP code

I have been working on my code with test.php that should trigger some Javascript when my PHP code, conditional.php, detects input and submits it. However, instead of executing the expected "Do Something in Javascript," it outputs "Not empty" instead. I fin ...

What is the process for implementing a click event and accessing the DOM within an iframe using react-frame-component?

I am working on using the react-frame-component to create an iframe. I am trying to bind a click event on the iframe and retrieve the DOM element with the id of "abc" inside the iframe. Can anyone guide me on how to achieve this? The code snippet provided ...

Check the feature that retrieves data from a `json` file

In my util file, I have a function that imports and checks whether a given sectionUUID has a video in the JSON file. import multipleVideos from '../data/videos.json' function hasSectionMultipleVideos (sectionUUID) { return multipleVideos.vide ...

Using JQUERY to store the ID of a div along with its checked value in a multidimensional array

I am looking to create an array that stores the ID of a div and the checked value. Check out this FIDDLE for reference For example, if I check samsung and lenovo under brands, and select 4gb for RAM, the array should be: array[ ] = ["brands" ...

When first accessing the page, the map may not load properly. However, a simple refresh of the page in VueJS should resolve this issue and allow the

After initially loading the page, the map may not work properly in Vue.js. However, refreshing the page fixes this issue. Can anyone provide assistance with this problem? Here is the relevant code: mounted() { this.geolocate(); }, methods: { ...

Seeking assistance in optimizing my Javascript code for more efficient canvas rendering

I've created a script for generating random moving lines as a background element for my portfolio. While it runs smoothly on its own, I encounter frame drops when combining it with other CSS animations and effects, especially at the beginning (althoug ...

Adjusting the size of the iframe to match the dimensions of the window

Is there a way to make the iframe automatically fill up the entire space? For example, only opens the iframe up to half of the window in Mozilla Firefox and IE6. How can I ensure that it takes the maximum size of the screen? Are there any CSS or JavaScr ...

Animate the appearance of list items sequentially using CSS animations

Is there a simpler way to achieve the effect of having list items slide in one after the other? The CSS method provided here seems quite intricate. #nav ul.is-visible{visibility:visible;opacity:1;-webkit-transform:scale(1);-ms-transform:scale(1);transfo ...

Choosing only those elements that are not children of parents with a specific class by utilizing the `.not()` method

I am attempting to target all elements having the class .select that are nested somewhere within the DOM tree. The only condition is that these elements should not have any ancestors with the class .forbidden. This means it will not detect any elements ...

What is the best way to define these variables at a global scope within my controller?

In my controller (NodeJS/Express), I have 10 routes that all use the same variables 'startDate' and 'endDate'. Is there a way to declare these globally so they don't need to be repeated in each route? Currently, my code checks if ...

"Efficiently handle online submissions: Use Django to submit a form and instantly display the outcome

I have an urgent task to develop a web page where users can input data, and the backend will perform calculations and display the result below the input field on the same page (similar to checking online air ticket prices). I am new to Django and HTML. Be ...

Transmitting an array through Socket.IO using the emit() method

I am currently developing an array in my socket io server and then transmitting it to the client. var roomList = io.sockets.manager.rooms; // creating a new Array to store the clients per room var clientsPerRoom = new Array(); //for (var i ...

Basic math tool using JSP/Servlet combination and Ajax

I have a follow-up question to my previous inquiry on Stack Overflow. I believe this topic deserves its own discussion due to the thorough response I received. My goal is to develop a straightforward calculator using JSP. The calculator will include two t ...

What is the best approach for promoting reusability in Angular: creating a new CSS class or a new component?

I have a div with a set of CSS properties that are essential to my application. These properties will be reused across multiple pages and components. <div style="display: flex; flex-direction: column; height: 100%"> //inner html will vary based on c ...

The module 'iap_verifier' could not be located

Setting up a new server using the following repository - https://github.com/surespot/web-server. I have successfully installed node.js, npm, CoffeScript, and all required dependencies. apt-get install nodejs npm npm install -g <a href="/cdn-cgi/l/email ...