Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to put items side by side

Short answer

Block elements stack on top of each other. display: flex on the parent lines them up in a row:

<div style="display: flex; gap: 8px;">
  <div style="padding: 12px; background: lavender;">One</div>
  <div style="padding: 12px; background: honeydew;">Two</div>
  <div style="padding: 12px; background: lightyellow;">Three</div>
</div>

Wrapping to a new line

With many items, flex-wrap: wrap moves the extra ones down instead of squeezing them:

<style>
  .tags { display: flex; flex-wrap: wrap; gap: 8px; width: 240px; }
  .tags span { padding: 4px 10px; background: gainsboro; border-radius: 12px; }
</style>
 
<div class="tags">
  <span>css</span><span>html</span><span>flexbox</span><span>grid</span><span>animation</span>
</div>

An image next to text

A common case is an avatar with a caption. align-items: center lines them up vertically:

<div style="display: flex; align-items: center; gap: 10px;">
  <img src="/media/photo-200x200.jpg" alt="" width="48" height="48" style="border-radius: 50%;">
  <span>Anna Smith</span>
</div>

Common mistake

People put display: flex on the items instead of the parent — and nothing changes. Flexbox is turned on at the container, and it is the container's direct children that line up.

Functions used in this recipe

  • display — Decides how an element behaves in the flow and how it lays out its content.
  • flex-wrap — Whether flex items may wrap onto new lines.
  • gap — The gaps between items in flexbox and grid.
  • align-items — Aligns items across the main axis — vertically in a row.

Thanks for reading!

Donate to the site — we work hard for you.