DEV Community

Syazwan
Syazwan

Posted on

How to Prevent Flexbox Items from Stretching to Full Width in Tailwind CSS

If you use flex and flex-col on a parent container, child elements will occupy the full width. This happens because the default value for align-items is stretch.

Why Do Child Elements Stretch?

When align-items is set to stretch, child elements fill the width of the parent container.

Example:

<form className="flex flex-col gap-2">
  <input className="border py-1 px-2" />
  <button className="border px-4 py-1 bg-slate-200">Submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode

Flexbox items stretched

In this example, the input, and button elements stretch to fill the width of the <form>.

Solutions

To prevent stretching, use either self-start on child elements or items-start on the parent element.

Option 1: Using self-start on Child Elements

The self-start class makes a child element align to the start of the cross axis:

<form className="flex flex-col gap-2">
  <input className="border py-1 px-2 self-start" />
  <button className="border px-4 py-1 bg-slate-200 self-start">
    Submit
  </button>
</form>
Enter fullscreen mode Exit fullscreen mode

Option 2: Using items-start on the Parent Element

The items-start class aligns all child elements to the start of the cross axis:

<form className="flex flex-col gap-2 items-start">
  <input className="border py-1 px-2" />
  <button className="border px-4 py-1 bg-slate-200">
    Submit
  </button>
</form>
Enter fullscreen mode Exit fullscreen mode

Flexbox items not stretched

Wraping Up

Using self-start on child elements or items-start on the parent container prevents flexbox items from stretching to fill the entire width.

Top comments (0)