m

Common CSS layouts using flex

September 11, 2023

Flex is a one-dimensional layout method for arranging items in rows or columns. Check out some basic principles, then take a look at examples of a few component layouts with flex.

Code in italics below indicates default values that may not always need to be explicitly specified.

  • css
  • development

Flex Rows

By default, the children of a flex container are placed in a row (left to right). They will grow or shrink shrink to fit the space available in their flex container.

Default behavior

Code

.flex-container { display: flex; flex-direction: row; gap: 1rem; }

Demo

Win-win.
We need to aspirationalise our offerings gain alignment, nor pull in ten extra bodies to help roll the tortoise first-order optimal strategies, so performance review, but upsell.

Equal width columns

We can get equal width columns in a flex container by specifying flex: 1; for each flex container child item.

Code

.flex-container { display: flex; flex-direction: row; gap: 1rem; } .flex-container > * { flex: 1; }

Demo

Win-win.
We need to aspirationalise our offerings gain alignment, nor pull in ten extra bodies to help roll the tortoise first-order optimal strategies, so performance review, but upsell.

Equal width columns with grid instead of flex

Please note that while the above method works most of the time, there will be occasions where it will fail. In those situations, using CSS grid may produce more consistent results.

Code

.grid-container { display: grid; gap: 1rem; grid-auto-columns: minmax(0, 1fr); grid-auto-flow: column; }

Demo

Win-win.
We need to aspirationalise our offerings gain alignment, nor pull in ten extra bodies to help roll the tortoise first-order optimal strategies, so performance review, but upsell.

Flex Columns

The children of a flex container can be placed in a column (top to bottom) by specifying flex-direction: column;.

Default behavior

Code

.flex-container { display: flex; flex-direction: column; gap: 1rem; }

Demo

Win-win.
We need to aspirationalise our offerings gain alignment, nor pull in ten extra bodies to help roll the tortoise first-order optimal strategies, so performance review, but upsell.

Component Layouts

Buttons and links with optional icons

See the Pen CSS layouts with flex - buttons and links with optional icons by Marina Ranenko πŸ‡ΊπŸ‡¦ (@mranenko) on CodePen.

Responsive navigation

See the Pen CSS layouts with flex - responsive navigation menu by Marina Ranenko πŸ‡ΊπŸ‡¦ (@mranenko) on CodePen.

Simple desktop website header

See the Pen CSS layouts with flex - equal height columns by Marina Ranenko πŸ‡ΊπŸ‡¦ (@mranenko) on CodePen.