Preserve font spacing for a line of text split into separate HTML elements
P粉258083432
P粉258083432 2023-09-10 18:37:01
0
1
673

I'm trying to recreate a common technique of splitting words into separate HTML elements so that they can be positioned individually via animation.

The problem I'm having is that I lose the spacing between the words when they are split into separate elements. I can add spacing by rendering with after each word, or by adding padding to each element, but I'd like to know if there is a way to do this without manually adding spacing/ Curving them onto the container and retaining the original spacing?

I know there are plugins like gsap SplitText, but I was hoping for a non-plugin solution.

Code pen is here.

const App = () => {
  const line = 'this is a line of text.';
  const renderLine = line.split(' ').map((word, i) => {
    return (
      <span key={i}>{word}&nbsp;</span>
    )
  })

  return (
    <h1>{renderLine}</h1>
  )
}

P粉258083432
P粉258083432

reply all(1)
P粉384679266

You can use the regular expression /\b/ This will search for word boundaries and split lines by words and spaces.

function App() {
  const line = "this is a line of text.";
  const renderLine = line.split(/\b/).map((word, i) => {
    return <span key={i}>{word}</span>;
  });

  return <h1>{renderLine}</h1>;
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template