The box model and flexbox

Here is the secret that makes CSS layout click: every element is a rectangle. Even a single word. Each box has four layers, from the inside out:

  1. content: the text or image itself
  2. padding: space inside the box, between the content and the border
  3. border: a line around the padding
  4. margin: space outside the border, pushing other boxes away
.card {
  padding: 16px;
  border: 2px solid black;
  margin: 10px;
}

border takes three values at once: thickness, style (solid, dashed, dotted) and colour. If you are ever confused about why something is the size it is, add a bright border to it. Professional developers do this daily and will deny it.

Flexbox

By default, block elements like <div> stack on top of each other. To put them side by side, make their parent a flex container:

.row {
  display: flex;
  justify-content: space-between;
  gap: 8px;
}

Now every direct child of .row sits in one horizontal line. The important bit: you put display: flex on the container, not on the children. The container is in charge of the layout.

justify-content decides how the children spread along the row:

  • flex-start: bunched at the start (the default)
  • center: bunched in the middle
  • space-between: first one at the start, last one at the end, even gaps between

gap adds space between the children without messing with their margins. align-items: center lines them up vertically in the middle, which is the famous "how do I centre a div" answer.

Try it yourself

Edit it. Break it. Run it again.
<style>
  .row {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 12px;
    background-color: #eeeeee;
    padding: 10px;
  }
  .card {
    padding: 16px;
    border: 2px solid teal;
    margin: 4px;
    background-color: white;
  }
</style>
<div class="row">
  <div class="card">One</div>
  <div class="card">Two</div>
  <div class="card">Three</div>
</div>
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Your turn

Type it yourself. That is the whole trick.

1Pad the box

Give .box a padding of 20px, a border of 2px solid black, and a margin of 10px.

<style>
  .box {
    background-color: lightblue;
  }
</style>
<div class="box">I need some breathing room.</div>
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

2Line them up

Make .row a flex container so the three items sit side by side, with justify-content set to space-between.

<style>
  .row {
    border: 1px solid gray;
  }
  .item {
    padding: 10px;
    background-color: orange;
  }
</style>
<div class="row">
  <div class="item">A</div>
  <div class="item">B</div>
  <div class="item">C</div>
</div>
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.