Intermediate
+30 XP

👋 Start learning JavaScript right now — for free!

📖

Flexbox — Container and Main Axis

display:flex, justify-content, align-items, gap

🎋

Flexbox — a flexible container

Imagine a tray with plates. You decide: arrange the plates in a row left to right, or in a column top to bottom, or spread them evenly across the tray. And the plates can be different sizes — but they always fit. Flexbox is that tray: you set the rules and the browser arranges the elements.

How to enable Flexbox

Add display: flex to the container (parent element). All direct child elements become flex items.

css
.container {
  display: flex;
}
html
<div class="container">
  <div>1</div>
  <div>2</div>   <!-- these are flex items -->
  <div>3</div>
</div>

flex-direction — main axis

css
flex-direction: row;           /* → left to right (default) */
flex-direction: row-reverse;   /* ← right to left */
flex-direction: column;        /* ↓ top to bottom */
flex-direction: column-reverse;/* ↑ bottom to top */

justify-content — alignment along the MAIN axis

css
justify-content: flex-start;    /* ← all left (default) */
justify-content: center;        /* || centred */
justify-content: flex-end;      /* → all right */
justify-content: space-between; /* |el   el   el| equal gaps between */
justify-content: space-around;  /* | el  el  el | gaps around each */
justify-content: space-evenly;  /* | el  el  el | equal gaps everywhere */

align-items — alignment along the CROSS axis

css
align-items: stretch;     /* stretched to full height (default) */
align-items: center;      /* vertically centred */
align-items: flex-start;  /* top */
align-items: flex-end;    /* bottom */
css
💬

gap replaces margin between flex items — much more convenient. flex: 1 1 300px — shorthand for flex-grow flex-shrink flex-basis.

To centre an element — display: flex + justify-content: center + align-items: center. This is the simplest centering method in CSS and it finally arrived after 20 years of hacks.

Comments

Log In or Start to leave a comment.