We've all come across projects or websites with poorly written code and have also had the pleasure starting a project on a clean slate. Any good front-end developer should care about writing clean and semantic code. Why? A few reasons include:
- Easier maintenance — Allows developers to make code updates easily.
- Increases page load speeds — Lesser code = Faster load.
- Improves SEO — Search engines can easily parse through site content and increase site rankings.
- ...and let's not forget, it improves the usability, which makes your users happy.
There are four approaches that I recently stumbled upon for writing organized and semantic code. Let's go ahead and take a look at what those are.
1. Object Oriented CSS (OOCSS)
The goal for OOCSS is to encourage code reuse for faster, more efficient and easier to maintain stylesheets. OOCSS is based on two principles:
- Separate structure and skin
- Separate container and content
2. Scalable & Modular Architecture for CSS (SMACSS)
There are two core goals for SMACSS:
- To increase the semantic value of a section of HTML and content
- Decrease the expectation of a specific HTML structure
3. Don't Repeat Yourself CSS (DRY CSS)
DRY CSS reorganizes the same selectors already used. Tags, classes, IDs should refer to content rather than how to content looks. Selectors and definitions should be as global as possible to prevent specificity collisions. DRY CSS also has a three step approach:
- Group reusable CSS properties and values
- Name these groups logically
- Add selectors to various groups
4. Block, Element, Modifier (BEM)
BEM decouples HTML and CSS by adding modifier classes to HTML, which can help create similar but different blocks. There are three guidelines for writing CSS:
- Blocks and elements should have unique names that become classes
- HTML elements shouldn't be used in CSS selectors as they aren't context-free
- Descendent selectors should be avoided
These approaches, at first, may seem a bit overwhelming. However, the funny thing is that you may have already been following these methods without even realizing it. My recommendation is to try one of these approaches so that you can start improving your site's performance and maintainability. Enjoy and happy coding!