Warum CSS formatieren?
Gut formatierter CSS-Code ist leichter zu lesen, zu debuggen und zu warten. Besonders minified CSS wird durch Formatierung wieder verständlich.
Formatierungsregeln
Einrückung
Properties werden innerhalb von Selektoren eingerückt. Standard: 2 oder 4 Leerzeichen.
.selector {
property: value;
another-property: value;
}Eine Property pro Zeile
/* Gut */
.button {
background: blue;
color: white;
padding: 10px;
}
/* Schlecht */
.button { background: blue; color: white; padding: 10px; }Leerzeichen
/* Empfohlen */
.selector {
property: value;
}
/* Nach Doppelpunkt ein Leerzeichen */
color: red; /* ✓ */
color:red; /* ✗ */Beispiel: Vorher/Nachher
Vorher (minified):
.nav{display:flex;gap:1rem}.nav a{color:#333;text-decoration:none}.nav a:hover{color:#007bff}Nachher (formatiert):
.nav {
display: flex;
gap: 1rem;
}
.nav a {
color: #333;
text-decoration: none;
}
.nav a:hover {
color: #007bff;
}CSS Coding Style Guides
- Airbnb CSS: Populär, gut dokumentiert
- Google CSS: Streng, konsistent
- BEM: Block-Element-Modifier Namenskonvention
- SMACSS: Scalable and Modular Architecture
Property-Sortierung
Übliche Reihenfolge (nach Typ):
- Positionierung: position, top, right, z-index
- Box Model: display, width, margin, padding
- Typografie: font, color, text-align
- Visuell: background, border, opacity
- Sonstiges: cursor, transition, animation
Automatische Formatierung
- Prettier: Opinionated, einfach einzurichten
- Stylelint: Linting + Fixing
- VS Code: Format Document (Shift+Alt+F)
- EditorConfig: Team-weite Einstellungen
Prettier-Konfiguration
// .prettierrc
{
"tabWidth": 2,
"useTabs": false,
"singleQuote": true
}Häufig gestellte Fragen
Tabs oder Leerzeichen?
Leerzeichen sind der Standard in den meisten Teams. Wichtiger als die Wahl ist Konsistenz – alle im Team sollten dasselbe nutzen.
Sollte ich CSS für Produktion formatieren?
Nein, für Produktion sollte CSS minified sein. Formatierter Code ist für Entwicklung, minified für Auslieferung.
Wie formatiere ich SCSS/Sass?
Dieselben Tools (Prettier, Stylelint) unterstützen auch SCSS. Bei verschachtelten Regeln wird die Einrückung entsprechend tiefer.