HTML/CSS Mastery

Flexbox Layouts

30 دقيقة

Flexbox arranges items in one direction: a row or a column. It is ideal for navigation bars, button groups, card contents and centring.

The basics

.toolbar {
  display: flex;
  align-items: center;        /* cross axis (vertical in a row) */
  justify-content: space-between;  /* main axis (horizontal in a row) */
  gap: 12px;
}
Property (container) Common values
flex-direction row, column
justify-content flex-start, center, space-between, flex-end
align-items stretch, center, flex-start, baseline
flex-wrap nowrap, wrap
gap spacing between items

Item sizing

.search { flex: 1; }          /* take the remaining space */
.logo { flex-shrink: 0; }     /* never shrink */
.sidebar { flex: 0 0 280px; } /* grow 0, shrink 0, basis 280px */

flex: 1 is shorthand for "grow to fill available space".

Centring anything

.center {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
}

A responsive navbar

.nav {
  display: flex;
  align-items: center;
  gap: 24px;
  padding: 16px 24px;
}
.nav .links { display: flex; gap: 16px; margin-left: auto; }

margin-left: auto on one item pushes it (and everything after it) to the far end, a very useful trick.

Cards with buttons aligned at the bottom

.card {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.card .actions { margin-top: auto; }   /* sticks to the bottom */

Combined with a grid of equal-height cards, every card's buttons line up.

Wrapping

.tags { display: flex; flex-wrap: wrap; gap: 8px; }

A common bug: overflowing flex items

Flex items have min-width: auto and will not shrink below their content, so a long URL or code block can overflow. Fix with min-width: 0 on the item (or overflow-wrap: anywhere on the text).

Exercise

Build a header with a logo on the left, a nav in the centre and two buttons on the right; a card whose button is always at the bottom; and a tag list that wraps. Resize the window and check nothing overflows.

Check yourself

  • Which property controls alignment along the main axis?
  • How do you push one item to the end of a row?
  • Why might a flex item overflow its container?

يُحفظ تقدّمك في هذا المتصفح فقط.

إرسال للمراجعة (10 نقطة)