LearnClean Up Your Code with Modular CSS

   
Treehouse

Treehouse
writes on March 8, 2018

CSS. It’s a web designer’s playpen. With so many colors, type settings, layout options, and responsive possibilities, it’s easy to turn a stylesheet into a million line nightmare. However, with a few simple actions you can clean up the mess so the CSS works with you, not against you. A few weeks ago, frontend developer Julie Cameron came through our virtual Treehouse office and bestowed some wisdom we still can’t shake. So now I’m sharing it with you all!


Tangled CSS

Your CSS may be a mess because…

It’s only natural. Entanglement happens.

The cascade. It’s a blessing and a curse. It’s often the case that when you change the styling of one element, other elements inadvertently get restyled. Misuse of !important makes the cascade come to a screeching halt, and leaves you with inconsistencies from one element styling to the next. As websites get bigger or more developers start working on the codebase, the CSS tends to grow as well. Without a plan, it becomes the Wild Wild West (wickey wild, wicky wicky wild wild wild west…Will Smith isn’t gonna get you out of this one).

Your CSS is tightly coupled with the HTML structure.

Another common mistake is to write CSS in the order the elements appear on the page. This may make sense when you’re cross-referencing a single page with its styling, but it falls apart once you consider multiple pages are using the same CSS. If there are multiple stylesheets, one per each page you’re in the same predicament. In a similar vein, overly specific CSS selectors also tend to mirror the HTML. This results in repetition and bloat…which leads to bad performance. None of this is scalable or maintainable.

You aren’t using Modular CSS

If your approach to writing CSS is to carefully craft the styling for each individual element, you’re missing the forest for the trees. Imagine peering out over a forest, noticing all the maple trees. You can write a class to style all those maple trees instead of crafting duplicate styles for each one. That’s how you can abstract your design into reusable chunks.

Now, imagine building a landing page without writing a single line of CSS. When your CSS is all encapsulated into reusable chunks, you’ve got a whole treasure trove of pre-styled pieces to choose from. But that’s just one of the perks. Julie highlighted all the joys of using Modular CSS:

  • Modular – You can get to the point of building a page without writing a single line of CSS.
  • Predictable – It doesn’t matter where you put the component, it’ll behave the same and look the same. It’s easy to write the code. You have systems in place for naming it. It’s more intuitive to write.
  • Maintainable – It’s quick and easy to deal with. It won’t break other things on the site.
  • Scalable – It’s hard to break and easy to build onto.
  • Dry – It eliminates the need for copy and paste duplication in the CSS.
  • Organized – There’s a place for everything.

Modular CSS

What is Modular CSS?

There are several modular solutions, but the one Julie mainly focused on is called OOCSS (Object Oriented CSS). It’s a scalable, maintainable, semantic, and predictable approach to writing CSS. Nicole Sullivan created it while working for Facebook. She set off to improve upon an unwieldy 10,000 line stylesheet. She began to see patterns in the styling, which led her to create a reusable module called the “media” object. By doing so, she proved she could save hundreds of lines of code. The media object is a content block containing a fixed-size media element (image or video) along with other variable-size content (text). Considering this is the predominant form of content on Facebook newsfeed, the opportunity for performance and maintainability improvement was huge!

OOCSS – Principles

The two main principles of OOCSS are: separation of structure from skin and separation of container from content.

Separation of structure from skin means to define the repeating patterns as reusable structures. For example, what makes a button look like a button? You might say, “rounded corners, padding, and a border.” Then you may have repeating visual patterns that serve as repeating skins. For example, you may have some blue buttons and red buttons. Those are two separate skins, as they each have a different background color.

Separation of container from content means that objects should look the same no matter where you put them. In other words, avoid location-dependent styles. For example, if you’re styling an h2 like this…

.categoryList h2 { styles }

.footer h2 { copied styles }

…you’re repeating the CSS in a way that’s hard to scale.

Here’s a better way to style the headers. You can reuse this styling, irregardless of the header’s placement:

.sectionHeader { reusable styles }

OOCSS – Objects

The foundation of OOCSS is objects, which is a piece of your design which can be reused throughout your site. Objects contain HTML, CSS, components like background images, and JavaScript (any behaviors, listeners, or methods associate with the object). Objects can be contained into Modules which may contain a base component with variations. For example, a basic button can have a .btn class, and also offer these variations: .btn-primary, .btn-inverse, .btn-warning, and so on. Here’s how it looks in context. Module components are structured in layers:

  • objects or modules or components
    .media
    • child objects (relationships)
      .media__img .media__body
      • modifiers (CSS design variations)
        .media--inline, .media__img--right
        • states (CSS or JS design adjustments)
          .media--collapsed, .media.is-active

OOCSS – Best Practices

As you’re considering what objects to build, Julie pointed out these best practices.

  1. Objects should have a single responsibility; they should do one thing well and one thing only.
  2. They should be completely encapsulated; the object should be able to stand on its own and work the same everywhere.
  3. Use classes for the object, modifier, and state. This allows you the flexibility to mix and match these without running the risk of being too specific.
  4. Pick a naming system and be consistent. There are different naming formats, so form a plan as a team. For example, camelCase or no camelcase? And how will you identify children, states, modifiers…the BEM way (.block__element--modifier)?
  5. Decide on using semantic and/or presentational naming. This is a hot topic, but it’s worthwhile to bring up to your team.

Semantics Arguments

  • Do classes have actual “semantic value?
  • To whom are classes semantic to?
  • Should classes always be semantic rather than presentational?
  • Is it better to have one semantic class or multiple mixed classes?
  • Example: .section-heading, .item-content

Presentational Arguments

  • Classes have NO meaning to the browser. It’s just used as a matching mechanism.
  • Classes ARE semantic to developers.
  • Presentational classes are reusable and don’t couple to content.
  • The content describes itself; classes don’t need to.
  • Example: .padding-top-large, .no-margin

What would you rather have?

  • Dry HTML (semantic) or Dry CSS (presentational)
  • Do you have any constraints, such as not being able to access to the CSS? Are you styling HTML that’s being spit out by a 3rd party tool?
  • You can use a mix of both. Using semantic module classes and presentational utility classes may be what works best for your team.

Get Started

How can I get started with Modular CSS?

Not sure where to start? Here are Julie’s tips on what to do next. These are great discussion points to bring up with your team, as you’ll want to carve out a plan that will work best for your situation. Then take small steps from there to start reaping the benefits of a modular system.

  1. Utilize a CSS preprocessor, such as Sass. Use partials, nesting, and mixins. These help to dry up the repetition.
  2. Establish conventions. Pick a naming system, categorization system, define code formatting standards, and document everything.
  3. Start iterating on abstracting your site. Start with base styles – html, body, p, a, h1-h6, etc. Then build block objects – lists, nav, buttons, media. After that, work on composite objects – headers, footers, masonry cards, sidebars.
  4. Continually isolate code until you find a comfortable level of granularity.
  5. Stop using CSS selectors for non-CSS (such as JavaScript, feature specs, etc).
  6. Architect a styleguide. Build components in the style guide before you build it in the app (helps to ensure encapsulation). It’s a good testing ground too to test out if a class is going to break something somewhere else.
  7. “Organize, optimize, repeat until you feel no pain” – Julie Cameron
  8. Keep in mind: Everyone does this differently. There are a lot of ideas and opinions. Play around and figure out what works best for you.

If you’d like to dig in even deeper, here’s Julie’s slide deck for the talk: Decoupling the Front-end with Modular CSS.


Recommended Courses

Learn more about Modular CSS:
New to Sass? Get started here:

More about Julie Cameron:

Julie has played various roles in the web development industry for over a decade and is currently working remotely in Ypsilanti, Michigan as a Tech Lead and Frontend Developer for Articulate. She is co-founder of the Ann Arbor chapter of Girl Develop It, and an experienced speaker and teacher, having presented at several national conferences and local Meetup groups. She is passionate about CSS, Sass, and modular frontend architecture; is an advocate for women in tech and life; she’s a yogi, a beer & wine consumer, a pet lover, a Beyoncé fan, and a self-improvement practitioner. Learn more about her at juliecameron.com, or follow her on Twitter at @jewlofthelotus.

GET STARTED NOW

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Get Started

3 Responses to “Clean Up Your Code with Modular CSS”

  1. Dave Dayanan on April 28, 2018 at 12:54 am said:

    Thanks for this piece of good advice. modular method help me lessens my time on bulk of projects that I had been working on.

  2. Philipp Vogel on April 11, 2018 at 12:35 am said:

    Hi there,

    good read – im really excited to take the relevant courses 😉

    Cheers from Germany!
    Philipp

  3. Thank you for such a wonderful writeup! So glad to have been able to share this knowledge with all of you!

Leave a Reply

You must be logged in to post a comment.

man working on his laptop

Are you ready to start learning?

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Start a Free Trial
woman working on her laptop