Patterns for CSS That Doesn't Devolve Into Chaos
Comments & Organization
CSS gets messy fast. A handful of conventions — naming, sectioning, file splitting — keep it readable.
What you'll learn
- Comment CSS effectively
- Group related rules
- Recognize BEM and utility-first conventions
CSS scales poorly without conventions. A few habits keep a stylesheet readable.
Comments
Single comment style:
/* Single-line */
/*
* Multi-line
* for longer notes
*/ Use comments for why, not what — your classes already say what.
/* Negative top margin pulls the image into the card's padding
so it can extend to the edges. */
.card-image { margin: -1rem -1rem 0; } Section Headers
Group related rules with a banner comment:
/* =========================================================
* Components — Card
* ========================================================= */
.card { … }
.card-header { … }
.card-body { … } Naming Patterns
BEM (Block, Element, Modifier)
.card { … } /* Block */
.card__title { … } /* Element */
.card--featured { … } /* Modifier */
.card__title--large { … } /* Modifier on element */ Reads loudly but the intent is unmistakable. Very common in hand-rolled CSS.
Utility-First (Tailwind-style)
<div class="p-4 rounded bg-white shadow">
<h2 class="text-xl font-bold">Title</h2>
</div> Inline composition. Less hand-written CSS, more thinking happens in the markup.
Plain Semantic
.card { … }
.card h2 { … }
.card.featured { … } Simpler, but specificity creeps. Fine for small projects.
File Structure
For projects beyond a single file:
styles/
├── base/
│ ├── reset.css
│ └── typography.css
├── components/
│ ├── button.css
│ ├── card.css
│ └── nav.css
├── utilities/
│ └── layout.css
└── main.css (imports the rest) main.css:
@import "./base/reset.css";
@import "./base/typography.css";
@import "./components/button.css";
@import "./components/card.css"; Or use cascade layers (covered in Modern CSS) to organize without splitting files.
Property Order
A common convention: position, then box, then visual, then type:
.card {
/* position */
position: relative;
/* box */
display: flex;
width: 300px;
padding: 1rem;
margin: 1rem 0;
/* visual */
background: white;
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 0 4px 12px rgb(0 0 0 / 10%);
/* type */
color: #111;
font-size: 1rem;
} Alphabetical also works — pick one and stick with it.
Up Next
Tools for debugging CSS when something doesn’t look right.
Debugging CSS →