Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to swap elements

Short answer

In a flex or grid container the order property sets the order. Everyone has 0 by default, a smaller value comes earlier:

<style>
  .row { display: flex; gap: 8px; }
  .row div { padding: 8px 16px; background: lavender; }
  .row .first { order: -1; background: gold; }
</style>
 
<div class="row">
  <div>One</div>
  <div>Two</div>
  <div class="first">Three</div>
</div>

Reversing the whole row

flex-direction: row-reverse or column-reverse lines up all the elements in reverse order:

<div style="display: flex; flex-direction: row-reverse; justify-content: flex-end; gap: 8px;">
  <span>1</span><span>2</span><span>3</span>
</div>

A different order on different screens

Most often the order changes in a media query: on a computer the image is to the right of the text, on a phone — above it:

<style>
  .media { display: flex; gap: 12px; }
  @media (max-width: 500px) { .media { flex-direction: column; } .media img { order: -1; } }
</style>
 
<div class="media">
  <p>Text about our flower shop.</p>
  <img src="/media/photo-200x200.jpg" alt="A flower" width="100" height="100">
</div>

In a grid the same is handy with grid-template-areas — only the area map changes.

Common mistake

order rearranges important elements — buttons, links, form fields. The eye sees the new order, but the Tab key and screen readers follow the HTML order: the focus starts jumping around the page. If the order matters for meaning, change it in the HTML itself.

Functions used in this recipe

  • order — Changes the visual order of a flex or grid item.
  • flex-direction — The direction of the main axis of a flex container: items in a row or in a column.
  • grid-template-areas — Draws the grid layout as a map of named areas.
  • display — Decides how an element behaves in the flow and how it lays out its content.

Thanks for reading!

Donate to the site — we work hard for you.