NelsonLabs
CSS Styling/Flexbox Layouts

Flexbox Layouts

Flexbox is the most practical layout tool in CSS. It solves the problems developers fought with for years: centering things, distributing space, aligning elements in a row or column.

ANALOGY

Items in a container. Think of a row of books on a shelf. Flexbox is you controlling that shelf โ€” how the books are spaced out, whether they start from the left, whether they're centred, whether one book stretches to fill the gap. The shelf is the flex container; the books are the flex items.

Flexbox fundamentals
css
/* Step 1: make a container a flex container */
.container {
  display: flex;
}
/* Now all direct children become flex items */

/* Direction */
flex-direction: row;           /* default โ€” left to right */
flex-direction: column;        /* top to bottom */
flex-direction: row-reverse;   /* right to left */
flex-direction: column-reverse;

/* Alignment along the main axis (horizontal if row) */
justify-content: flex-start;   /* default โ€” pack to start */
justify-content: flex-end;     /* pack to end */
justify-content: center;       /* centre */
justify-content: space-between; /* equal gaps between items */
justify-content: space-around;  /* equal space around items */
justify-content: space-evenly;  /* perfectly even gaps */

/* Alignment along the cross axis (vertical if row) */
align-items: stretch;          /* default โ€” items fill height */
align-items: flex-start;       /* align to top */
align-items: flex-end;         /* align to bottom */
align-items: center;           /* vertically centre */
align-items: baseline;         /* align text baselines */

/* Wrapping when items overflow */
flex-wrap: nowrap;             /* default โ€” shrink to fit */
flex-wrap: wrap;               /* wrap to new line */
Centering โ€” solved forever
css
/* The classic "centred both ways" โ€” finally easy */
.centred {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* Full screen centred hero */
.hero {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
Flex item properties
css
/* Control individual items inside a flex container */

.item {
  flex-grow: 1;    /* how much the item can grow to fill space */
  flex-shrink: 1;  /* how much the item can shrink if needed */
  flex-basis: 0;   /* starting size before growing/shrinking */

  /* Shorthand: flex: grow shrink basis */
  flex: 1;         /* grow: 1, shrink: 1, basis: 0 โ€” equal columns */
  flex: 0 0 200px; /* fixed 200px, doesn't grow or shrink */
  flex: 1 0 auto;  /* grows, doesn't shrink, natural size */
}

/* Override the container's align-items for one item */
.sidebar { align-self: flex-start; }
.main    { align-self: stretch; }