Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

295
Views
How can I scatter each letter to a random position inside a container using CSS and javaScript?

I have few letters which I want to scatter inside a container randomly, but I'm unable to find how I can get hold of each letter and change its CSS to fix random position inside the container. My code is as below:

import React, { useState, useEffect } from "react";
import "./styles.css";


// Splitting Texts
const SplitText = React.memo(({ str }) => {
  return (
    <div>
      {str.split("").map((item, index) => {
        return <div key={index}>{item}</div>;
      })}
    </div>
  );
});

function debounce(fn, ms) {
  let timer;
  return (_) => {
    clearTimeout(timer);
    timer = setTimeout((_) => {
      timer = null;
      fn.apply(this, arguments);
    }, ms);
  };
}

// Main App
export default function App() {
  //Getting the window width and height using useEffect
  const [dimensions, setDimensions] = useState({
    height: window.innerHeight,
    width: window.innerWidth
  });

  useEffect(() => {
    const debouncedHandleResize = debounce(function handleResize() {
      setDimensions({
        height: window.innerHeight,
        width: window.innerWidth
      });
    }, 1000);

    window.addEventListener("resize", debouncedHandleResize);

    return (_) => {
      window.removeEventListener("resize", debouncedHandleResize);
    };
  }); //useEffect End

  //define random position on screen
  var randLeft = Math.floor(Math.random() * dimensions.width);
  var randTop = Math.floor(Math.random() * dimensions.height);
  console.log(randLeft);
  console.log(randTop);

  return (
    <div className="container">
      <h1>
        <SplitText str={"Lucie Bachman"} />
      </h1>
      <h2>
        <SplitText str={"Hey, this is my first post on StackOverflow!"} />
      </h2>
    </div>
  );
}

The desired output should be like in this CodePen

Link to my working Sandbox: Click

Any suggestion on how I can get hold of each letter would be of great help.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!