Sub topic 2
Organising Files and Folders
Assume you know CSS selectors, the box model, inheritance, specificity, and basic npm usage. At scale, organisation should make a rule’s reach clear before you read its declarations.
Organising files and folders
Separate styles by responsibility and expected reach:
styles/
settings/
tokens.css
generic/
reset.css
elements/
forms.css
objects/
layout.css
components/
card.css
button.css
utilities/
spacing.css
main.cssA useful rule is that lower-level folders should not depend on higher-level folders. A reset should not style a component. A component may use a token, but a token should not know about a component.
Layered architectures
Several CSS architectures describe similar boundaries with different vocabulary.
- ITCSS orders styles from low specificity and wide reach to high specificity and narrow reach: settings, tools, generic rules, elements, objects, components, and utilities.
- SMACSS groups rules as base, layout, module, state, and theme.
- OOCSS separates structure from appearance. For example, a reusable layout object can be combined with a visual component.
These systems are guides, not mandatory folder names. Choose one vocabulary and document it. Mixing terms without clear boundaries makes ownership harder to understand.
Controlling order with `@layer`
The cascade decides which declaration wins. Cascade layers let you define that order explicitly, without increasing selector specificity.
@layer reset, base, components, utilities;
@layer reset {
* {
box-sizing: border-box;
}
}
@layer components {
.card {
padding: 1rem;
}
}
@layer utilities {
.p-0 {
padding: 0;
}
}Here, .p-0 wins over .card because utilities comes later, even though both selectors have the same specificity. Keep the layer order in one central file.
Design tokens with custom properties
A design token is a named value for a repeated design decision, such as a color or spacing unit. CSS custom properties store tokens in the browser and let components consume them.
:root {
--color-text: #1a1a1a;
--color-accent: #0b5fff;
--space-2: 0.5rem;
--space-4: 1rem;
}
.button {
color: var(--color-text);
padding: var(--space-2) var(--space-4);
border: 2px solid var(--color-accent);
}Changing a token updates every consumer. Name tokens by purpose when possible, such as --color-accent, rather than by a particular component.
Exercise
Which layer should contain a reusable .card rule, and how can a utility override it safely?
Show answer
Put .card in the components layer and declare a later utilities layer, such as @layer components, utilities;.