skip to Main Content

How can I make the <h1> elements take on the next line if the width of the parent element becomes too small?

EXAMPLE:

Each word here is an <h1>element. They are spaced by their parent <div> using display: flex; and gap: 1rem;.
enter image description here

Now, the width of the parent <div> is reduced, so how can I make the other <h1> elements occupy the next line like the image below?
enter image description here

CODE:

<div className="flex gap-4">
    {
        text.split(" ").map((e, i) => (
            <h1 key={i} className="text-color-1 text-3xl font-bold text-center lg:text-left md:text-5xl lg:text-7xl whitespace-pre-line inline">
                {e}
            </h1>
        ))
    }
</div>

2

Answers


  1. Consider applying flex-wrap: wrap to the <div> element via the flex-wrap Tailwind utility class:

    const text = 'This is an example';
    
    ReactDOM.createRoot(document.getElementById('app')).render(
      <div className="flex gap-4 flex-wrap">
        {text.split(' ').map((e, i) => (
          <h1
            key={i}
            className="text-color-1 text-3xl font-bold text-center lg:text-left md:text-5xl lg:text-7xl whitespace-pre-line inline"
          >
            {e}
          </h1>
        ))}
      </div>
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.0/umd/react.production.min.js" integrity="sha512-ZA7si8ER+VYYp/DB0qHGoBUUHww+JcrRLyNhlLHpZOnvWZppaUp7TgKT3VRb7TUhOwE9I4RTdGesYYYM0U73CQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.0/umd/react-dom.production.min.js" integrity="sha512-ZezdfPGeFUpe5Och082E7dtOcO51kZtQmF7skp34UfOkROcAWXhQZ4pHODBBXDF01jSjskWy5B9z8z2GGTqsPw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdn.tailwindcss.com/3.4.3"></script>
    
    <div id="app"></div>
    Login or Signup to reply.
  2. I would just remove the whitespace-pre-line inline classes.

    html, body { width: 100%; height: 100%; }
    <script src="https://cdn.tailwindcss.com"></script>
    <body class="flex w-full h-full items-center justify-center bg-neutral-900">
      <div class="w-48 bg-red-700">
        <h1 class="text-color-1 text-3xl font-bold text-center lg:text-left md:text-5xl lg:text-7xl">This is some example text</h1>
      </div>
    </body>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search