Writing CSS is one thing, but writing maintainable CSS that others (or future you) can understand is another. Good CSS organization and proper commenting are essential skills for professional web development. Let's learn how to write CSS that's easy to read, maintain, and scale.
CSS Comments
Comments in CSS are annotations that explain your code. They're ignored by browsers and serve only to help developers understand the stylesheet. Good comments make your code self-documenting and easier to maintain.
Comment Syntax
CSS comments start with /* and end with */. Everything between these markers is ignored by the browser.
/* This is a single-line comment */
/*
This is a multi-line comment.
You can write as many lines as you need.
The browser will ignore all of this.
*/
/* Basic styling for paragraphs */
p {
color: #333;
line-height: 1.6;
}
/*
Button styles
- Primary action buttons
- Used throughout the site
*/
.button {
background-color: #667eea;
color: white;
padding: 12px 24px;
}Important: Unlike HTML comments <!-- --> or JavaScript comments // or /* */, CSS only supports the /* */ syntax. There are no single-line comment shortcuts in CSS.
When to Use Comments
Comments are valuable in several situations:
- Explaining complex code: Clarify tricky CSS techniques or hacks
- Documenting decisions: Explain why you chose a particular approach
- Organizing sections: Create clear divisions in your stylesheet
- Temporary removal: Disable styles while testing without deleting them
- Team collaboration: Help other developers understand your code
- Future reference: Leave notes for yourself when you revisit the code
- Browser compatibility notes: Document browser-specific fixes
Types of Comments
1. Section Headers
Use prominent comments to divide your stylesheet into logical sections:
/* ========================================
TYPOGRAPHY
======================================== */
body {
font-family: Arial, sans-serif;
}
h1, h2, h3 {
font-weight: bold;
}
/* ========================================
LAYOUT
======================================== */
.container {
max-width: 1200px;
margin: 0 auto;
}
/* ========================================
COMPONENTS
======================================== */
.card {
background: white;
padding: 20px;
}2. Subsection Dividers
For smaller divisions within major sections:
/* =========================
BUTTONS
========================= */
/* --- Primary Buttons --- */
.btn-primary {
background-color: #667eea;
color: white;
}
/* --- Secondary Buttons --- */
.btn-secondary {
background-color: #gray;
color: white;
}
/* --- Button States --- */
.btn:hover {
opacity: 0.9;
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}3. Explanatory Comments
Explain what the code does and why:
/*
Use flexbox to center the content both
horizontally and vertically
*/
.center-content {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
/*
Fix for Safari's default button styling
which adds unwanted border-radius
*/
button {
border-radius: 0;
-webkit-appearance: none;
}
/*
Z-index hierarchy:
- Modal overlay: 1000
- Modal content: 1001
- Dropdown menus: 100
- Navigation: 50
*/
.modal-overlay {
z-index: 1000;
}4. TODO and Notes
Mark items that need attention or future work:
/* TODO: Update these colors to match new brand guidelines */
:root {
--primary-color: #667eea;
--secondary-color: #764ba2;
}
/* FIXME: This causes layout shift on mobile devices */
.hero-image {
width: 100%;
height: auto;
}
/* NOTE: This is a temporary fix until we refactor the navigation */
.temp-nav-fix {
position: relative;
z-index: 999;
}
/* HACK: IE11 fallback - remove when IE11 support is dropped */
.grid-container {
display: -ms-grid; /* IE11 */
display: grid; /* Modern browsers */
}5. Inline Comments
Brief explanations next to specific properties:
.card {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* Subtle shadow for depth */
transition: transform 0.3s; /* Smooth hover animation */
}
.card:hover {
transform: translateY(-5px); /* Lift card on hover */
}
.navigation {
position: sticky; /* Stick to top when scrolling */
top: 0;
z-index: 100; /* Above content, below modals */
}6. Commented-Out Code
Temporarily disable styles for testing:
/* Old button styles - keeping for reference
.button-old {
background: linear-gradient(to right, #667eea, #764ba2);
padding: 15px 30px;
font-size: 18px;
}
*/
/* New simplified button styles */
.button {
background-color: #667eea;
padding: 12px 24px;
font-size: 16px;
}
/* Temporarily disabled while testing new layout
.sidebar {
width: 300px;
position: fixed;
right: 0;
}
*/💡 Best Practice:
Don't leave commented-out code in production. Either delete it or use version control (like Git) to track old code. Keeping dead code clutters your stylesheet and confuses other developers.
Comment Style Guide
Consistent Formatting
Choose a comment style and stick with it throughout your project:
/* Style 1: Box style for major sections */
/* ========================================
MAJOR SECTION
======================================== */
/* Style 2: Line style for subsections */
/* --- Subsection --- */
/* Style 3: Simple comments for explanations */
/* This is a simple explanation */
/* Style 4: Multi-line block comments */
/*
* Component: Button
* Description: Primary call-to-action button
* Usage: <button class="btn-primary">Click me</button>
*/Comment Length Guidelines
Keep comments clear and concise:
/* Good: Clear and concise */
/* Center content vertically and horizontally */
/* Avoid: Too verbose */
/*
This rule will center the content both vertically
and horizontally within the container using flexbox,
which is a modern CSS layout method that provides
an easy way to align items...
*/
/* Good: Straight to the point */
/* Fix Safari button styling issue */
/* Avoid: Unclear */
/* This fixes something */Avoid Over-Commenting
Don't comment obvious things:
/* Bad: States the obvious */
.red-text {
color: red; /* Makes the text red */
}
/* Bad: Unnecessary */
.container {
width: 100%; /* Set width to 100% */
padding: 20px; /* Add 20px padding */
}
/* Good: Only comment what needs explanation */
.container {
width: 100%;
padding: 20px;
contain: layout; /* Optimize rendering performance */
}Organizing CSS Files
1. Single File Structure
For small projects, organize a single CSS file with clear sections:
/* ========================================
TABLE OF CONTENTS
1. CSS Variables
2. Reset & Base Styles
3. Typography
4. Layout
5. Components
6. Utilities
7. Media Queries
======================================== */
/* ========================================
1. CSS VARIABLES
======================================== */
:root {
--primary-color: #667eea;
--secondary-color: #764ba2;
--text-color: #333;
--background-color: #f4f4f4;
--spacing-unit: 8px;
}
/* ========================================
2. RESET & BASE STYLES
======================================== */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', sans-serif;
color: var(--text-color);
background-color: var(--background-color);
}
/* ========================================
3. TYPOGRAPHY
======================================== */
h1, h2, h3, h4, h5, h6 {
font-weight: bold;
line-height: 1.2;
}
h1 { font-size: 2.5rem; }
h2 { font-size: 2rem; }
h3 { font-size: 1.75rem; }
p {
line-height: 1.6;
margin-bottom: 1rem;
}
/* ========================================
4. LAYOUT
======================================== */
.container {
max-width: 1200px;
margin: 0 auto;
padding: 0 var(--spacing-unit);
}
.grid {
display: grid;
gap: calc(var(--spacing-unit) * 2);
}
/* ========================================
5. COMPONENTS
======================================== */
/* --- Buttons --- */
.btn {
padding: 12px 24px;
border: none;
border-radius: 5px;
cursor: pointer;
transition: all 0.3s;
}
.btn-primary {
background-color: var(--primary-color);
color: white;
}
/* --- Cards --- */
.card {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
/* ========================================
6. UTILITIES
======================================== */
.text-center { text-align: center; }
.mt-1 { margin-top: var(--spacing-unit); }
.mb-1 { margin-bottom: var(--spacing-unit); }
/* ========================================
7. MEDIA QUERIES
======================================== */
@media (max-width: 768px) {
/* Tablet and mobile styles */
}
@media (max-width: 480px) {
/* Mobile-only styles */
}2. Multiple File Structure
For larger projects, split CSS into multiple organized files:
css/
│
├── main.css (Imports all other files)
│
├── base/
│ ├── reset.css (Browser resets)
│ ├── variables.css (CSS custom properties)
│ ├── typography.css (Font and text styles)
│ └── base.css (Base element styles)
│
├── layout/
│ ├── grid.css (Grid system)
│ ├── header.css (Header styles)
│ ├── footer.css (Footer styles)
│ └── navigation.css (Navigation styles)
│
├── components/
│ ├── buttons.css (Button components)
│ ├── cards.css (Card components)
│ ├── forms.css (Form elements)
│ └── modals.css (Modal dialogs)
│
├── pages/
│ ├── home.css (Home page specific)
│ ├── about.css (About page specific)
│ └── contact.css (Contact page specific)
│
└── utilities/
├── helpers.css (Helper classes)
└── responsive.css (Media queries)Then import them in your main CSS file:
/* ========================================
MAIN STYLESHEET
Imports all CSS modules
======================================== */
/* Base styles */
@import url('base/reset.css');
@import url('base/variables.css');
@import url('base/typography.css');
@import url('base/base.css');
/* Layout */
@import url('layout/grid.css');
@import url('layout/header.css');
@import url('layout/footer.css');
@import url('layout/navigation.css');
/* Components */
@import url('components/buttons.css');
@import url('components/cards.css');
@import url('components/forms.css');
@import url('components/modals.css');
/* Pages */
@import url('pages/home.css');
@import url('pages/about.css');
@import url('pages/contact.css');
/* Utilities */
@import url('utilities/helpers.css');
@import url('utilities/responsive.css');Note: While @import works, it can slow down page loading because files load sequentially. In production, consider using a CSS preprocessor like Sass or a build tool to combine files, or link multiple CSS files directly in HTML.
CSS Architecture Methodologies
Several popular methodologies help organize CSS for large projects:
1. BEM (Block Element Modifier)
A naming convention that makes CSS classes more readable and maintainable:
/* Block: Standalone component */
.card { }
/* Element: Part of a block */
.card__header { }
.card__body { }
.card__footer { }
/* Modifier: Variation of a block or element */
.card--featured { }
.card--large { }
.card__header--dark { }
/* Complete example */
.card {
background: white;
border-radius: 8px;
}
.card__header {
padding: 20px;
border-bottom: 1px solid #eee;
}
.card__body {
padding: 20px;
}
.card--featured {
border: 2px solid gold;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}2. SMACSS (Scalable and Modular Architecture for CSS)
Organizes CSS into five categories:
/* 1. Base Rules - Element defaults */
body { font-family: Arial, sans-serif; }
a { color: blue; }
button { cursor: pointer; }
/* 2. Layout Rules - Major page sections (prefix: l-) */
.l-header { }
.l-sidebar { }
.l-content { }
.l-footer { }
/* 3. Module Rules - Reusable components */
.card { }
.button { }
.nav { }
/* 4. State Rules - How things look in different states (prefix: is-) */
.is-active { }
.is-hidden { }
.is-collapsed { }
/* 5. Theme Rules - Color schemes and visual themes */
.theme-dark { }
.theme-light { }3. OOCSS (Object-Oriented CSS)
Separates structure from skin, container from content:
/* Structure (layout, positioning) */
.box {
padding: 20px;
margin-bottom: 20px;
}
/* Skin (visual appearance) */
.box-primary {
background-color: #667eea;
color: white;
}
.box-secondary {
background-color: #gray;
color: white;
}
/* Usage: Combine structure and skin */
/* <div class="box box-primary">...</div> */
/* <div class="box box-secondary">...</div> */
/* Container (independent of content) */
.media {
display: flex;
gap: 20px;
}
.media-image {
flex-shrink: 0;
}
.media-body {
flex: 1;
}4. Utility-First CSS
Uses small, single-purpose utility classes (popularized by Tailwind CSS):
/* Spacing utilities */
.m-1 { margin: 8px; }
.m-2 { margin: 16px; }
.mt-1 { margin-top: 8px; }
.mb-2 { margin-bottom: 16px; }
/* Display utilities */
.flex { display: flex; }
.grid { display: grid; }
.hidden { display: none; }
/* Typography utilities */
.text-center { text-align: center; }
.text-lg { font-size: 18px; }
.font-bold { font-weight: bold; }
/* Color utilities */
.text-primary { color: #667eea; }
.bg-white { background-color: white; }
/* Usage: Combine utilities */
/* <div class="flex mt-2 mb-2 text-center">...</div> */🎯 Choosing a Methodology:
You don't need to follow these methodologies strictly, especially as a beginner. However, understanding them helps you write more organized CSS. Many developers combine elements from different methodologies to create their own system.
Naming Conventions
General Guidelines
- Use lowercase letters and hyphens (kebab-case)
- Make names descriptive and meaningful
- Be consistent throughout your project
- Avoid abbreviations unless widely understood
- Use prefixes for clarity when needed
/* Good: Clear, descriptive names */
.navigation-menu { }
.hero-section { }
.call-to-action-button { }
.user-profile-card { }
/* Avoid: Unclear abbreviations */
.nav-mn { }
.h-sec { }
.cta-btn { }
.usr-prof-crd { }
/* Good: Descriptive class names */
.text-center { }
.bg-primary { }
.border-rounded { }
/* Avoid: Presentational names tied to specific values */
.blue-text { } /* What if you change to red? */
.margin-20 { } /* What if you change to 16px? */
.font-18 { } /* What if you change to 20px? */
/* Better: Semantic names */
.text-primary { }
.spacing-md { }
.text-lg { }Prefixing Conventions
Use prefixes to indicate purpose or category:
/* Layout prefixes */
.l-header { }
.l-sidebar { }
.l-main { }
/* Component prefixes */
.c-button { }
.c-card { }
.c-modal { }
/* Utility prefixes */
.u-text-center { }
.u-hidden { }
.u-margin-top { }
/* State prefixes */
.is-active { }
.is-loading { }
.is-disabled { }
/* JavaScript hooks (don't style these) */
.js-toggle { }
.js-dropdown { }
.js-slider { }Code Formatting Best Practices
Property Order
Organize properties in a logical order for consistency:
/* Recommended order:
1. Positioning
2. Box Model
3. Typography
4. Visual
5. Misc
*/
.element {
/* Positioning */
position: absolute;
top: 0;
right: 0;
z-index: 100;
/* Box Model */
display: flex;
width: 100%;
height: 50px;
margin: 20px;
padding: 10px;
/* Typography */
font-family: Arial, sans-serif;
font-size: 16px;
line-height: 1.6;
text-align: center;
/* Visual */
background-color: white;
border: 1px solid gray;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
/* Misc */
cursor: pointer;
transition: all 0.3s;
}Indentation and Spacing
Use consistent indentation and spacing:
/* Good: Consistent 2-space indentation */
.card {
background: white;
padding: 20px;
}
.card-header {
font-size: 24px;
margin-bottom: 10px;
}
/* Good: Space after colons */
.element {
color: blue;
margin: 10px;
}
/* Avoid: No spacing */
.element{
color:blue;
margin:10px;
}
/* Good: One property per line */
.button {
background-color: blue;
color: white;
padding: 10px 20px;
}
/* Avoid: Multiple properties per line */
.button { background-color: blue; color: white; padding: 10px 20px; }Selector Formatting
Format selectors consistently:
/* Good: One selector per line for readability */
h1,
h2,
h3,
h4,
h5,
h6 {
font-weight: bold;
}
/* Good: Clear nesting indication */
.navigation {
background: #333;
}
.navigation .nav-item {
padding: 10px;
}
.navigation .nav-item.active {
color: gold;
}
/* Avoid: All on one line when multiple selectors */
h1, h2, h3, h4, h5, h6 { font-weight: bold; }File Documentation Headers
Start CSS files with documentation headers:
/**
* Project: My Awesome Website
* File: main.css
* Description: Main stylesheet for the entire website
* Author: Your Name
* Created: 2024-01-15
* Last Modified: 2024-01-20
* Version: 2.1.0
*
* Dependencies:
* - normalize.css v8.0.1
* - Google Fonts: Roboto
*
* Browser Support:
* - Chrome (latest)
* - Firefox (latest)
* - Safari (latest)
* - Edge (latest)
*/
/* ========================================
TABLE OF CONTENTS
1. Variables
2. Reset & Base
3. Typography
4. Layout
5. Components
5.1 Buttons
5.2 Cards
5.3 Forms
6. Utilities
7. Media Queries
======================================== */Complete Practical Example
Here's a well-organized, properly commented CSS file:
/**
* Component: Product Card
* Description: Displays product information with image, title, price
* Usage: <div class="product-card">...</div>
* Dependencies: None
*/
/* ========================================
PRODUCT CARD COMPONENT
======================================== */
/* --- Base Card Styles --- */
.product-card {
/* Layout */
display: flex;
flex-direction: column;
/* Box Model */
max-width: 300px;
padding: 20px;
margin: 0 auto;
/* Visual */
background: white;
border-radius: 12px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
/* Animation */
transition: transform 0.3s, box-shadow 0.3s;
}
/* Lift card slightly on hover for interactivity */
.product-card:hover {
transform: translateY(-5px);
box-shadow: 0 8px 12px rgba(0, 0, 0, 0.15);
}
/* --- Card Image --- */
.product-card__image {
/* Ensure image fills container width */
width: 100%;
height: 200px;
object-fit: cover; /* Maintain aspect ratio */
border-radius: 8px;
margin-bottom: 15px;
}
/* --- Card Content --- */
.product-card__title {
font-size: 20px;
font-weight: bold;
color: #333;
margin-bottom: 10px;
/* Limit to 2 lines with ellipsis */
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.product-card__description {
font-size: 14px;
color: #666;
line-height: 1.6;
margin-bottom: 15px;
/* Limit to 3 lines */
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
.product-card__price {
font-size: 24px;
font-weight: bold;
color: #667eea;
margin-bottom: 15px;
}
/* Strike-through for original price */
.product-card__price-original {
font-size: 16px;
color: #999;
text-decoration: line-through;
margin-left: 10px;
}
/* --- Card Actions --- */
.product-card__button {
/* Make button fill width */
width: 100%;
padding: 12px;
background-color: #667eea;
color: white;
border: none;
border-radius: 6px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: background-color 0.3s;
}
.product-card__button:hover {
background-color: #5568d3;
}
.product-card__button:active {
transform: scale(0.98); /* Slight press effect */
}
/* --- Modifiers --- */
/* Featured variant with accent border */
.product-card--featured {
border: 2px solid gold;
}
/* Sale variant with red accent */
.product-card--sale .product-card__price {
color: #e74c3c;
}
/* Out of stock state */
.product-card--out-of-stock {
opacity: 0.6;
}
.product-card--out-of-stock .product-card__button {
background-color: #ccc;
cursor: not-allowed;
}
/* ========================================
MEDIA QUERIES
======================================== */
/* Tablet and below */
@media (max-width: 768px) {
.product-card {
max-width: 100%; /* Full width on smaller screens */
}
}
/* Mobile */
@media (max-width: 480px) {
.product-card__image {
height: 150px; /* Smaller image on mobile */
}
.product-card__title {
font-size: 18px;
}
.product-card__price {
font-size: 20px;
}
}Tools and Automation
Code Formatters
Use tools to automatically format your CSS:
- Prettier: Automatic code formatter
- Stylelint: CSS linter to enforce rules
- CSS Comb: Sort CSS properties consistently
- EditorConfig: Maintain consistent coding styles
Editor Extensions
Visual Studio Code extensions that help:
- CSS Peek - Jump to CSS definitions
- IntelliSense for CSS - Auto-completion
- Color Highlight - Preview colors in code
- CSS Navigation - Navigate CSS with ease
Common Organization Mistakes
1. No Organization
/* Bad: Random order, no structure */
.button { background: blue; }
.card { padding: 20px; }
h1 { font-size: 32px; }
.button:hover { background: darkblue; }
p { line-height: 1.6; }
.card-title { font-weight: bold; }2. Inconsistent Naming
/* Bad: Mixed naming conventions */
.productCard { }
.product-image { }
.ProductTitle { }
.product_price { }3. No Comments on Complex Code
/* Bad: Complex code with no explanation */
.element {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* Good: Explained */
/* Center element both horizontally and vertically */
.element {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}4. Leaving Dead Code
/* Bad: Keeping old unused code */
/* .old-button { }
.deprecated-card { }
.unused-style { } */
/* Good: Delete it or use version control */Key Takeaways
- CSS comments use /* */ syntax and are ignored by browsers
- Use comments to explain complex code, document decisions, and organize sections
- Organize CSS files with clear sections and table of contents
- For large projects, split CSS into multiple organized files
- Consider using methodologies like BEM, SMACSS, or OOCSS
- Use consistent naming conventions (lowercase with hyphens)
- Format code consistently with proper indentation and spacing
- Order properties logically (positioning, box model, typography, visual)
- Don't over-comment obvious things or leave dead code
- Use tools like Prettier and Stylelint to automate formatting
- Well-organized CSS is easier to maintain and scale
What's Next?
Congratulations! You've completed the "Getting Started" section of the CSS tutorial. You now understand what CSS is, how to write CSS syntax, the different methods of adding CSS to HTML, and how to organize and document your CSS code.
In the next section, we'll dive into CSS Selectors and Specificity, where you'll learn how to target HTML elements precisely and understand how CSS determines which styles to apply when rules conflict. This is fundamental knowledge for writing effective CSS!
🎉 Well Done!
You've built a solid foundation in CSS basics. The habits you develop now—writing clean, organized, well-commented code—will serve you throughout your entire web development career. Keep practicing these principles!