Μετάβαση στο κύριο περιεχόμενο
← 🎨 CSS as a design system·Ενότητα B2 · Μάθημα 12
ΕργασίαBuild a nav bar: 4 links Home / Pricing / Docs / Log in. .nav with display: flex, gap: 16px. The .login link should be pushed to the right via margin-left: auto. Add padding 12px 24px and background #18181B with white text.

Μοτίβο: περιθώριο-αριστερό αυτόματο για "ώθηση προς τα δεξιά"

75 XP5 min
Θεωρία

The trick that saves nav bars

A flex row of links where ONE specific link should sit at the far right while the others sit on the left:

<nav class="nav">
  <a>Home</a>
  <a>Pricing</a>
  <a>Docs</a>
  <a class="login">Log in</a>
</nav>

You COULD use justify-content: space-between but that spreads ALL of them apart evenly. You want most-clumped-left, ONE on the right.

.nav { display: flex; gap: 16px; }
.login { margin-left: auto; }    /* absorbs all empty space on the left */

Done. The auto margin eats all available main-axis space, pushing .login to the right edge.

Why it works

A flex item with margin-left: auto (or any "auto" margin) GETS as much free space as possible BEFORE positioning. So the empty space between the previous items and .login expands to fill the gap.

Other variants

.center-me { margin-left: auto; margin-right: auto; }   /* hug center via auto on both sides */
.bottom-of-column {                                      /* in flex column */
  margin-top: auto;
}

Compare to space-between

Both produce "far apart" layouts but differently:

  • justify-content: space-between distributes ALL items evenly.
  • margin-left: auto on one child pushes ONLY that child away. Others stay clumped.

Use the second when you have "primary nav on the left, account on the right" patterns.

🔒

Εγγράψου για να αρχίσεις να προγραμματίζεις

Η θεωρία είναι ανοιχτή για όλους. Ο επεξεργαστής, η ζωντανή προεπισκόπηση και ο έλεγχος ξεκλειδώνουν με 7-ήμερη δωρεάν δοκιμή — απαιτείται κάρτα.

Εγγραφή — δωρεάν δοκιμή →

Τα πρώτα 10 μαθήματα κάθε διαδρομής είναι δωρεάν. Δεν χρειάζεται κάρτα.

← ΠροηγούμενοΕπόμενο μάθημα →

Μια συμβουλή Python ή web την ημέρα — με email

Σύντομο, γραμμένο στο χέρι, χωρίς spam. Διαγραφή με ένα κλικ.