Center elements using Flexbox, even the elements in the last row by using
flex flow-row flex-wrap justify-center
classes.
This layout centers its *child* div both vertically and horizontally using Flexbox.
export default function LayoutFlexCenter() {return (<div className="border-1 flex flow-row flex-wrap justify-center"><div className="border-1 p-4 m-4"><h1>Flexbox Centering</h1><p>This layout centers its *child* div both vertically and horizontally using Flexbox.</p></div><div className="border-1 p-4 m-4"><h1>Horizontal</h1><img src="https://placehold.co/250x100" /></div><div className="border-1 p-4 m-4"><h1>Vertical</h1><img src="https://placehold.co/100x250" /></div></div>);}
This layout centers everything both vertically and horizontally using Flexbox.
export default function LayoutFlexCenter() {return (<div className="border-1 flex flow-row flex-wrap justify-center text-center items-center"><div className="border-1 p-4 m-4"><h1>Flexbox Centering</h1><p>This layout centers everything both vertically and horizontally using Flexbox.</p></div><div className="border-1 p-4 m-4"><h1>Horizontal</h1><img src="https://placehold.co/250x100" /></div><div className="border-1 p-4 m-4"><h1>Vertical</h1><img src="https://placehold.co/100x250" /></div></div>);}
items-stretch will stretch the divs to the same height.
flex-1 will make the divs take equal width.
After these 2 changes, the images are left aligned instead of center, whereas the texts are centered.
The reason is that Tailwind’s Preflight resets make <img>
a block‐level element
by default, and block elements don’t obey their parent’s text-align. Your .text-center
is centering inline text but has no effect on a block <img>
. To center those images you can for example add mx-auto
:
Ref: https://stackoverflow.com/questions/67417275/cards-of-same-height-in-tailwind-css
This layout centers everything both vertically and horizontally using Flexbox.
export default function LayoutFlexCenterEqualWidth() {return (<div className="border-1 flex flow-row flex-wrap justify-center text-center items-center items-stretch"><div className="flex-1 border-1 p-4 m-4"><h1>Flexbox Centering</h1><p>This layout centers everything both vertically and horizontally using Flexbox.</p></div><div className="flex-1 border-1 p-4 m-4"><h1>Horizontal</h1><img src="https://placehold.co/250x100"className="mx-auto"/></div><div className="flex-1 border-1 p-4 m-4"><h1>Vertical</h1><img src="https://placehold.co/100x250"className="mx-auto"/></div></div>);}