This article is part of a series created in partnership with SiteGround. Thank you for supporting the partners who make SitePoint possible.
In this article, I’m going to discuss three successful approaches to CSS architecture, their principles, goals and advantages.Key Takeaways
- BEM, SMACSS, and ECSS are three methodologies that can be used to manage CSS architecture, each with its own principles, goals, and benefits.
- BEM (Block-Element-Modifier) focuses on easy project maintenance over time and components reusability, organizing CSS code into reusable modules with a smart naming convention.
- SMACSS (Scalable and Modular Architecture for CSS) categorizes CSS rules to identify patterns and create guidelines for coding maintainable and reusable CSS, with a flexible naming convention that aids in code organization and team productivity.
- ECSS (Enduring CSS) emphasizes isolation, encapsulating all the code necessary to build each component in its own shared folders and using a strict CSS naming convention. This methodology supports easy maintenance and minimal file size increases in the long run.
Why Can CSS Code Spiral Out of Control?
Keeping CSS code lean, re-usable and maintainable is notoriously hard. If you neglect to enforce any coding and organizational rules in a consistent way, this can be the case both for small and medium to big projects, where more than one developer is at work. Where the codebase is large, goes through a number of changes over time, and organization is lacking, it often happens that teams prefer to add new style rules at the end of the style sheet document rather than remove chunks of it or modify what’s already there. The main reason is often that the effects of editing or removing CSS declarations can be unpredictable and risk breaking the design somewhere in the project. This is a losing strategy, which can lead to code duplication, specificity issues where overriding style rules turns into a battle, and overall bloat. Most often than not, choosing the methodology that most suits your needs is an iterative process, which starts with getting familiar with what’s already out there. Here are three methodological approaches to help you fight the challenges of a messy style sheet.BEM
BEM stands for Block-Element-Modifier. It is a methodology for architecting CSS created by Yandex. The goal of the BEM methodology isto develop sites which should be launched fast and supported for a long time. It helps to create extendable and reusable interface components. BEM websiteThe key concepts here are easy project maintenance over time, and components reusability. The core BEM strategy consists in organizing CSS code into reusable modules with the help of a smart naming convention. Let’s have a closer look.
What Is a Block?
Identifying blocks is a crucial step of applying the BEM methodology. A block is afunctionally independent page component that can be reused. In HTML, blocks are represented by the class attribute. BEM docs.When deciding what to consider a block, ask yourself if you can easily remove that portion of code and use it somewhere else. For instance, you can consider a website header or footer to be a block. You can safely nest blocks, for instance, you can place a menu block inside a header block.
<header>
<ul class="menu">
<!-- menu items here -->
</ul>
</header>
Because in principle you should be able to reuse blocks anywhere in your page, your CSS for the block should not set any margins or positioning rules.
Finally, when choosing a name, make sure the name describes what the block is for, what its purpose is, never what its appearance or state is. In other words, its name should answer the question: What is it? (e.g., a header, a menu, etc.), not What does it look like? (e.g., fixed header, small menu, etc.).
What Is an Element?
According to the BEM methodology, an Element isA part of a block that has no standalone meaning and is semantically tied to its block. Get BEMHere are a few principles applying to elements:
- Elements only live inside a block
- Elements cannot belong to other elements, they can only be part of a block
- You can build nested elements
- Element names describe their purpose, not their appearance
- When naming elements, you need to follow this conventions:
block__element
What Is a Modifier?
A Modifier isAn entity that defines the appearance, state, or behavior of a block or element. BEM docsFor instance, a header block can be fixed to the top of the page , an accordion block can be open or closed, a button block can be disabled, etc. The BEM naming convention for modifiers looks like this:
block__element_modifier
.
This is the core of the BEM methodology. In addition, BEM offers principles of file structure organization, a suite of tools, and a lively community for support.
Pros of Using BEM
These are some advantages of using BEM in your projects- New developers can quickly understand the relationship between a component in markup and CSS rules
- It facilitates productivity in teams. The benefit is especially noticeable when working on larger projects
- The naming convention reduces the risks of class name collisions and style leaks
- CSS is not closely tied to the markup in a specific location inside the page
- CSS is highly reusable
SMACSS
Scalable and Modular Architecture for CSS, or SMACSS, is a web development methodology for organizing and writing CSS code. Its creator, Jonathan Snook, describes it as follows:SMACSS is a way to examine your design process and as a way to fit those rigid frameworks into a flexible thought process. It is an attempt to document a consistent approach to site development when using CSS. SMACSS WebsiteAt its core is a way of categorizing CSS rules. Categorization brings forth patterns, i.e., things you see repeated more than once in the design, around which you can work out guidelines for coding maintainable and reusable CSS. SMACSS core categories are:
- Base — In this category belong CSS rules that govern the default appearance of elements. Selectors include single element selectors, attribute selectors, pseudo-class selectors, sibling selectors, etc. For instance,
html
,body
,a, a:hover
, etc. - Layout — This category is for styles used to divide the page into sections.
- Module — Modules are the reusable lego-like parts of the design, e.g., menu, dialog, search box, etc.
- State — This category includes styles to describe what the layout or modules look like when in a particular state (e.g., visible or hidden, expanded or closed, etc.) or in a particular view (e.g., Home page or inner page)
- Theme — this category is similar to State in so far as it includes CSS rules that take care of layouts’ and modules’ appearance. Not all projects need this extra category, but it’s good to know it’s there.
SMACSS Naming Convention
Related to the categories outlined above, SMACSS proposes a naming convention to help with code organization and dev teams productivity. Layout, State and Module rules are prefixed with a meaningful name or abbreviation. For Layout rules, something likelayout-
, grid-
, or even simply l-
are acceptable prefixes.
For State rules, the convention is to prefix the state with is-
, e.g., is-hidden
, is-visible
, etc.
As for Modules, just use the name of the component you’re building, e.g., .menu
, .dialog
, etc.
For instance, to style an open dialog box, you can use a selector like .dialog.is-open
in your CSS. Related elements inside a module, as well as variations of the same module, should use the module’s base name as a prefix. Also, try not to use Ids, element selectors, or nested selectors. For instance, to select a menu item inside a module called menu, instead of writing your selector like this: .menu li a
, use something like this: .menu-link
or .menu-item
.
Unlike BEM, SMACSS doesn’t prescribe an overly-strict naming convention. Jonathan Snook makes this clear as he claims:
… don’t feel like you have to stick to these guidelines rigidly. Have a convention, document it, and stick to it. SMACSS Website
Advantages of Using SMACSS
Some advantages of the SMACSS approach to CSS coding are:- It offers valid guidelines for modular, maintainable CSS while avoiding to be overly-prescriptive
- You can learn (and teach) SMACSS quickly
- SMACSS naming convention is less verbose and in some ways easier to come to grips with than BEM’s
- It’s flexible enough to work well for both large and small projects
ECSS
Enduring CSS or eCSS isA guide to writing style sheets for large scale, rapidly changing, long-lived web projects. eCSS WebsiteThis CSS methodology has really piqued my interest for the original perspective taken by its author, Ben Frain, on the challenge of dealing with CSS at scale. A central concept of eCSS is isolation. Isolation means that each component is an insulated unit of code with no dependency, no contextual baggage, reusable and removable without risk of causing style leaks. This is achieved mainly by
- Encapsulating all the code, not just CSS, but all the technologies you need to build each component, in its own shared folders.
- Creating a brand new component each time you need a component similar to one already in place, but with some variations, even if the variations are slight.
- Using a strict CSS naming convention
Benefits of Using eCSS
Here’s what you can gain from applying the eCSS methodology and embracing its view of repetition:- By keeping each visual pattern isolated, the CSS code becomes easier to maintain
- Although you find repeated properties and values, file size increases remain minimal in the long run. This is so because modules are self-contained, isolated units that you can quickly remove when you don’t need them anymore, without fear of breaking the design
- All language/technology files necessary to create a module share the same folder, making both editing and physically removing what’s no longer needed, extremely easy.
Conclusion
Writing maintainable and well organized CSS code has its challenges. In this article I’ve presented three methodologies that can help with the task. It’s by no means an exhaustive list and none of these approaches solves all the problems you might come across while working on a project. Just try them out and see what works for you. You can also try using BEM and SMACSS together, or even work out your own methodology on the basis of the specific set of problems you set yourself to solve. What are your golden rules for writing organized, manageable CSS code? Do you think using a methodology for CSS architecture can ease the pain? Hit the comment box to let me know.Frequently Asked Questions on CSS Architecture Methodologies
What are the key differences between OOCSS, SMACSS, and BEM methodologies?
OOCSS, SMACSS, and BEM are all CSS methodologies designed to help developers write clean, maintainable, and scalable CSS. OOCSS, or Object-Oriented CSS, encourages developers to write reusable, object-oriented code. It focuses on separating structure from skin and separating container from content. SMACSS, or Scalable and Modular Architecture for CSS, provides guidelines for categorizing CSS rules to make your code more flexible and manageable. BEM, or Block Element Modifier, is a naming convention that makes your CSS easier to read and understand. It divides the UI into independent blocks, which can be reused and combined.
How can I implement WordPress coding standards in CSS?
WordPress has its own set of coding standards for CSS to ensure consistency and readability across different projects. These standards include rules for naming conventions, indentation, spacing, and comments. To implement these standards, you can use a CSS linter like Stylelint with the WordPress configuration.
What is the role of a StyleSheet in web development?
A StyleSheet is a file or form of code that defines the layout and design of a webpage. It controls the visual presentation of HTML elements on the page, including layout, colors, fonts, and animations. CSS (Cascading Style Sheets) is the most commonly used StyleSheet language.
How can CSS methodologies improve my web design process?
CSS methodologies can greatly improve your web design process by making your CSS more organized, reusable, and scalable. They provide a structured approach to writing CSS, which can help reduce the complexity of your code, make it easier to understand and maintain, and improve performance.
What are the best practices for writing CSS in HTML?
The best practices for writing CSS in HTML include separating style from content by using external style sheets, using selectors effectively, grouping related styles, using shorthand properties, and commenting your code for clarity. It’s also important to validate your CSS to ensure it’s free of errors and compatible with different browsers.
How can I make my CSS code more maintainable?
To make your CSS code more maintainable, you can use a CSS methodology like OOCSS, SMACSS, or BEM, which provide guidelines for structuring and organizing your code. Other strategies include modularizing your CSS, using a preprocessor like Sass or Less, and following naming conventions.
What are the advantages of using a CSS preprocessor?
CSS preprocessors like Sass and Less allow you to use variables, nesting, mixins, and functions in your CSS, which can make your code more readable and maintainable. They also allow you to write more concise and powerful CSS.
How can I ensure my CSS is compatible with different browsers?
To ensure your CSS is compatible with different browsers, you can use tools like Can I Use, which shows the compatibility of CSS properties across different browsers. It’s also important to use vendor prefixes for CSS properties that are not fully supported by all browsers.
What is the importance of CSS in web design?
CSS is crucial in web design as it controls the visual presentation of the content on a webpage. It allows you to create visually appealing websites with consistent design and layout. It also enables you to adapt the presentation to different types of devices, such as desktops, tablets, and mobile phones.
How can I learn more about CSS methodologies?
There are many resources available online to learn about CSS methodologies. Websites like SitePoint, Smashing Magazine, and Mozilla Developer Network offer in-depth articles and tutorials. You can also find online courses on platforms like Coursera and Udemy.
Maria Antonietta Perna is a teacher and technical writer. She enjoys tinkering with cool CSS standards and is curious about teaching approaches to front-end code. When not coding or writing for the web, she enjoys reading philosophy books, taking long walks, and appreciating good food.