search

Home  >  Q&A  >  body text

Preserve font spacing for a line of text split into separate HTML elements

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粉258083432P粉258083432489 days ago694

reply all(1)I'll reply

  • P粉384679266

    P粉3846792662023-09-11 17:16:51

    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>

    reply
    0
  • Cancelreply