Search code examples
cssreactjstextgradient

Is it possible to set horizontal gradient to text via CSS? (left letter one colour, right - another colour)


Is it possible to set horizontal gradient to text via CSS? (left letter one colour, right - another colour).


Solution

  • Yes, it is.

    h1 {
      font-size: 72px;
       background: -webkit-linear-gradient(left, red , yellow);
       background: -o-linear-gradient(right, red, yellow);
       background: -moz-linear-gradient(right, red, yellow);
       background: linear-gradient(to right, red , yellow); 
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }
    <h1>Hello World</h1>

    Example using React and styled-components:

    const ColorText = styled.h1 `
      font-size: 72px;
      background: linear-gradient(to right, red , yellow); 
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    `;
    
    const App = () => (
      <ColorText>Colorful Text</ColorText>
    );
    
    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>
    <script crossorigin src="//unpkg.com/styled-components/dist/styled-components.min.js"></script>