If you've ever tried to sketch out object-oriented designs in plain text and wished for a cleaner way to do it, Mermaid's class diagram syntax is exactly what you need. Being able to write class diagrams as code means your designs live alongside your source code, get version-controlled, and update without needing a separate diagramming tool. This article walks through real class diagram Mermaid code examples so you can start modeling systems right away.
What does a class diagram in Mermaid look like?
A class diagram in Mermaid is a text-based diagram that describes classes, their attributes, methods, and the relationships between them. You write simple markup using the classDiagram keyword, and Mermaid renders it visually. It follows the Unified Modeling Language (UML) conventions most developers already know.
Here's a minimal example:
classDiagram
class Animal
Animal : +String name
Animal : +makeSound()
This creates a single class called Animal with one attribute (name) and one method (makeSound()). The + sign indicates public visibility, following standard UML notation.
How do you define a class with attributes and methods?
You can define class members in two ways. The first uses the colon syntax shown above. The second places members inside curly braces right after the class name:
classDiagram
class Car {
+String brand
+int year
+start()
+stop()
}
Both approaches produce the same result. The curly brace style is often easier to read when a class has many members.
Visibility markers follow UML conventions:
- + means public
- - means private
- # means protected
- ~ means package/internal
You can also include data types and return types in method signatures:
classDiagram
class BankAccount {
-String owner
-float balance
+deposit(float amount) void
+withdraw(float amount) float
+getBalance() float
}
How do you show relationships between classes?
Relationships are the core reason class diagrams exist. Mermaid uses arrow syntax to connect classes. Here are the main relationship types:
classDiagram
Animal <|-- Dog
Animal <|-- Cat
Owner "1" -- "many" Pet
Car o-- Wheel
Driver ..> Car
Breaking down each symbol:
<|--means inheritance (Dog extends Animal)--means composition (Pet is owned by Owner and can't exist independently)o--means aggregation (Wheel belongs to Car but can exist separately)-->means association (a standard relationship)..>means dependency (Driver uses Car)--means link (solid)..means link (dashed)
You can label relationships and specify multiplicity:
classDiagram
Department "1" --> "0.." Employee : employs
Employee --> Project : works on
Employee "1" --> "1" Address : lives at
The quoted numbers describe multiplicity. "1" means exactly one, "0.." means zero or more, and "1.." means one or more. This mirrors how you'd annotate relationships in a traditional UML tool.
Can you add notes and abstract classes?
Yes. Mermaid supports abstract classes, interfaces, and annotations. Here's a more complete example showing these features:
classDiagram
class Shape {
<>
+area() float
+perimeter() float
}
class Drawable {
<>
+draw() void
}
class Circle {
-float radius
+area() float
+perimeter() float
+draw() void
}
class Rectangle {
-float width
-float height
+area() float
+perimeter() float
+draw() void
}
Shape <|-- Circle
Shape <|-- Rectangle
Drawable <|.. Circle
Drawable <|.. Rectangle
The <<abstract>> and <<interface>> annotations use angle brackets and display as stereotypes in the rendered diagram, just like you'd see in a standard UML diagram.
What does a real-world class diagram example look like?
Here's a practical example modeling a basic e-commerce system:
classDiagram
class Customer {
+int id
+String name
+String email
+placeOrder() Order
+viewOrders() List~Order~
}
class Order {
+int orderId
+Date createdAt
+float total
+addItem(Product, int) void
+calculateTotal() float
+getStatus() OrderStatus
}
class OrderItem {
+int quantity
+float unitPrice
+getSubtotal() float
}
class Product {
+int productId
+String name
+float price
+int stock
+isAvailable() bool
}
class OrderStatus {
<>
PENDING
PAID
SHIPPED
DELIVERED
CANCELLED
}
Customer "1" --> "0.." Order : places
Order "1" -- "1.." OrderItem : contains
OrderItem "1" --> "1" Product : references
Order "1" --> "1" OrderStatus : has
Notice how the tilde syntax List~Order~ represents generics, since angle brackets conflict with Mermaid's stereotype syntax. The enumeration is declared using the <<enumeration>> stereotype.
How do you style class diagrams in Mermaid?
You can add CSS-based styling to individual classes using the style keyword or define CSS classes and apply them:
classDiagram
class CriticalService {
+process() void
}
class OptionalService {
+process() void
}
CriticalService --> OptionalService
style CriticalService fill:#f96,stroke:#333,stroke-width:2px
style OptionalService fill:#bbf,stroke:#333
For broader styling across your diagrams, you can check our Mermaid diagram editor and tool comparison to find editors that offer live previews and easier styling workflows.
What are common mistakes when writing class diagrams in Mermaid?
Here are pitfalls that trip up both beginners and experienced developers:
- Forgetting the class declaration. If you reference a class in a relationship but never declared it with the
classkeyword or implicitly through a relationship, Mermaid may not render it as expected. Always define your classes. - Using angle brackets for generics. Mermaid treats
<and>as syntax for stereotypes and inheritance arrows. Use~for generic types instead (e.g.,List~String~). - Mixing indentation styles. Mermaid's parser can be sensitive to indentation inside curly brace blocks. Keep your indentation consistent.
- Confusing composition and aggregation. Composition (
--) means the child can't exist without the parent. Aggregation (o--) means the child can. Choosing the wrong one misrepresents your system design. - Omitting relationship labels. Unlabeled relationships make diagrams hard to understand. Always add a label after the colon.
- Overcomplicating a single diagram. Trying to model an entire system in one class diagram defeats the purpose. Break diagrams into focused views.
How do you render Mermaid class diagrams?
You have several options for rendering your Mermaid code:
- GitHub and GitLab both render Mermaid code blocks in markdown files automatically
- VS Code with the Mermaid extension gives you live preview
- The official Mermaid Live Editor at mermaid.live lets you paste code and see the diagram instantly
- Static site generators like Docusaurus and MkDocs have built-in Mermaid support
If you're deciding which tool fits your workflow best, our online tool comparison covers the main options side by side.
What's the difference between class diagrams and other Mermaid diagram types?
Class diagrams describe static structure what classes exist, what they contain, and how they relate. They're different from behavioral diagrams. For example:
- Sequence diagrams show how objects interact over time (message passing). If you need to model runtime behavior, sequence diagrams in Mermaid are the better choice.
- Flowcharts show process flows, not data structures
- ER diagrams model database tables and relationships, not object-oriented classes
Many teams use class diagrams during design and architecture discussions, then switch to sequence diagrams when discussing specific interactions or flows.
Can you use namespaces or group classes together?
Mermaid supports namespaces, which help organize large diagrams:
classDiagram
namespace DataAccess {
class UserRepository {
+findById(int) User
+save(User) void
}
class OrderRepository {
+findByCustomer(int) List~Order~
}
}
namespace BusinessLogic {
class UserService {
+register(User) void
}
class OrderService {
+createOrder(int) Order
}
}
UserService --> UserRepository
OrderService --> OrderRepository
OrderService --> UserService
Namespaces render as visual containers around grouped classes, making it easier to see architectural boundaries.
Quick checklist for writing class diagrams in Mermaid
- Start every diagram with the
classDiagramkeyword on its own line - Use curly braces to define classes with members for readability
- Add visibility markers (
+,-,#,~) to all members - Use
~instead of<>for generic types - Label every relationship with a descriptive verb phrase
- Include multiplicity on relationships where it matters
- Use
<<abstract>>,<<interface>>, and<<enumeration>>stereotypes where appropriate - Break large models into multiple focused diagrams
- Render your diagram early and often using a live editor to catch syntax errors fast
- Store your
.mmdor markdown files in version control alongside your code
For a deeper look at all class diagram syntax variations, our complete Mermaid syntax reference covers every option available.
How to Create Sequence Diagrams in Mermaid Markdown
Best Online Mermaid Diagram Editors: Syntax and Tool Comparison Guide
Mermaid Syntax Cheat Sheet for Flowcharts
Mermaid Js State Diagram Syntax Reference Guide
E-Commerce Website Database Schema Diagram Example with Tables and Relationships
Beginner's Guide to Graphviz Dot Language Syntax