Ugrás a fő tartalomra
A Frontend ingyenes bónusz a CodeMentor AI-n — a fő termék a Python. Regisztrálj a haladásod mentéséhez és nyisd meg mind a 299 Frontend leckét + 1,100+ Python leckét.Regisztrálj — ingyen
← 🎨 CSS as a design system·Modul B1 · Lecke 4
FeladatThe .alert text should be red. There's a more-specific rule trying to make it blue. Use !important on .alert to force red. (The blue rule stays — we're demonstrating !important wins.)

!fontos: mikor szag, mikor megfelelő

75 XP6 minFREE
Elmélet

What !important does

Tacks an !important flag on the declaration. Important declarations are compared in a separate pass that comes first: they beat every normal declaration, whatever its specificity. Between two !important declarations the usual tie-breakers apply — but note that the origin and layer order are REVERSED: an important user-agent or user rule beats an important author rule, and inside the author origin an important rule in an *earlier* @layer beats an important rule in a later layer (and layered important beats unlayered important). Only then does specificity and source order decide.

.alert { color: red !important; }

After this, NO normal declaration can override the color. Not #main .alert, not inline style="color: blue". Only another !important declaration can — one from a higher origin (user/browser), an earlier layer, or with higher specificity / later position in the same layer.

When !important is a smell

90% of !important usage is a sign the codebase has lost the specificity fight. Junior dev can't override something → adds !important → later someone needs to override THAT → adds !important higher up → arms race.

The fix is almost always: increase your selector's specificity by one class level, or rewrite the conflicting rule to be less specific.

When !important is actually correct

Three legitimate uses:

  1. Utility classes (Tailwind-style). A class like .text-center { text-align: center !important; } is meant to ALWAYS win. The rule "if you applied this utility, you wanted it" is honest.
  2. User stylesheets / accessibility overrides. A user setting * { font-size: 18px !important } to enforce a minimum font size — beats anything the site author tried.
  3. Print stylesheets. @media print { * { background: none !important } } to ensure printers don't waste ink on dark themes.

Outside these three, treat !important as a code smell that needs investigation.

How to UN-important

You can't lower a declaration's importance. The only options:

  1. Remove the !important from the source.
  2. Outrank it with another !important (higher specificity, a more important origin, or an earlier layer).

The second is the arms race we're trying to avoid. The first is the right answer.

2 lapok
Élő előnézet
← ElőzőKövetkező lecke →

Egy Python- vagy webes tipp naponta — emailben

Rövid, kézzel írt, spam nélkül. Egy kattintással leiratkozhatsz.