Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to make a sidebar layout

Short answer

One fixed-width column and one for everything else:

<style>
  .layout { display: grid; grid-template-columns: 160px 1fr; gap: 12px; }
  .layout aside { padding: 12px; background: lavender; }
  .layout main { padding: 12px; background: whitesmoke; }
</style>
 
<div class="layout">
  <aside>Categories</aside>
  <main>Article text goes here.</main>
</div>

A flexible sidebar width

clamp() keeps the sidebar from getting too narrow or too wide:

.layout { grid-template-columns: clamp(140px, 25%, 260px) 1fr; }

The sidebar on a phone

Two columns are cramped on a narrow screen. Use one column by default and switch to two with a media query:

<style>
  .wrap { display: grid; gap: 12px; }
  .wrap aside { padding: 12px; background: lavender; }
  .wrap main { padding: 12px; background: whitesmoke; }
  @media (min-width: 480px) { .wrap { grid-template-columns: 160px 1fr; } }
</style>
 
<div class="wrap"><aside>Filters</aside><main>Products</main></div>

Common mistake

If main gets a long unbroken string or a wide table, the 1fr column stretches and pushes the page sideways: grid items have a minimum width equal to their content. Write minmax(0, 1fr) instead of 1fr so the column can shrink.

Functions used in this recipe

  • grid-template-columns — The number and widths of the columns of a grid.
  • minmax() — A grid track size between a minimum and a maximum.
  • clamp() — Keeps a value within limits: the preferred value, but not less than the minimum and not more than the maximum.
  • @media — Applies rules only under given conditions — the window width, the system theme and others.

Thanks for reading!

Donate to the site — we work hard for you.