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

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>

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>

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>

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.

Please follow and like us:
Pin Share