A Modern Approach to CSS Pt. 1: Tools and Organization

css tools

The use of Sass on compiled themes is being deprecated, and stylesheets should migrate to native CSS features. For more information on this change and how to use Sass locally in your theme development workflow, please read our announcement blog post ondeprecating Sass.

Over the last several years web technologies have experienced a surge in advancement. With so much rapid change, it can be difficult to know what to focus on and just as difficult to not become overwhelmed by the amount of change. I’ve watched as my colleagues, and I as well, have focused on only specific areas of development in an attempt to try and stay on top of the latest the web has to offer.

My primary focus during this period of advancement has been CSS. I’ve learned a lot about tooling, naming conventions, and systems—things that never crossed my mind when writing CSS a decade ago. The style layer of the web has never been more complex and complicated than it is now, and navigating what goes into modern CSS development can be difficult. In this two-part series, I’ll share what I’ve learned and how I like to approach writing and creating CSS today. Part one will cover CSS tools and organization methods to help you level up your CSS writing.

Grow your business with the Shopify Partner Program

Whether you offer web design and development services or want to build apps for the Shopify App Store, the Shopify Partner Program will set you up for success. Join for free and access revenue share opportunities, developer preview environments, and educational resources.

Sign up

CSS tooling

The landscape for CSS tools has changed significantly sinceSassfirst came along and started challenging how we viewed writing CSS. Within a couple of years of Sass’ debut, we also hadLessandStylusto choose from. Today withPostCSSandCSS-in-JS, we have even more CSS tooling resources than it seems we know what to do with.

CSS is not a programming language on its own. Rather, CSS is akin to HTML and provides information to the browser which is read and rendered linearly. At the time thatpreprocessors—programs that generate CSS—became available, CSS had no way to provide common values in a reusable manner. Each instance of a color, font, or a spacing value in a stylesheet had to be painstakingly tracked by the developer. CSS tooling provides a way for programming principles to be applied to the style writing, with a common intent of generating a CSS file artifact which browsers can read.

Sass

Preprocessors began the shift toward programmatic CSS and are still highly useful and used today despite other options appearing on the scene. Sass remains the most commonly used preprocessor. It’s the one I prefer and will be speaking of most in this article. The second place goes to Less, the preprocessor used for customizing the text editorAtom. Sass started out as Ruby gem, but today is maintained equally in two programming languages,DartandC. This shift has allowed Sass to flourish as Ruby’s popularity has waned over the last few years.

css tools: sass
Sass remains the most commonly used preprocessor. Head tosass-lang.comto install it.

Sass provides numerous features, and any one can be enough to cause a developer to consider using it. For now I’ll list my top 5 with a brief explanation for each.

1.Mixins:Sass mixins are versatile code snippets that can output lists of CSS properties and even programmatic selectors, complete with properties that can be passed into the mixin.

2.Functions:Allow a similar level of programming, but in the end can only return a single value.

3.Variables:A very common reason for using Sass is the variables feature. Sass also provides a couple of other features that tie in with the concept of a variable:

  • Maps:The way to create a simple set of key/value pairs or an array of values is through the use of Maps.
  • Parent Selector:Sass uses the ampersand(&) to act as a sort of local variable that represents the selector scope up to that point when nesting selectors.

    4.Loops and Conditionals:Sass provides a way to loop over data, via Maps or counting, as well as check that values meet the right criteria. This may be basic programming, but simplifies so much for a CSS developer.

    5.Color Functions:The tour de force of Sass in my mind remains to be the many ways to manipulate a hex value. For a designer these functions are invaluable and provideeasy ways to color adjust the designfor specific needs and situations.

      If you have never used Sass before, a resource I use regularly when teaching Sass or working through a problem with Sass is a website calledSassmeister. It works similar to other web-based code editors, but its primary focus is to generate and display the compiled CSS. It enables you to see visually how Sass features create CSS, which makes it a helpful tool for learning and debugging.

      Over the last few years, Node has grown to become the de facto build system for front end artifact creation. With that popularity, Node-based CSS tools have appeared. For me that started withlibSass,C implementation of Sass, but quickly the toolset includedPostCSS. The PostCSS project provides a framework to traverse and manipulate the CSS tree.

      By far the most useful PostCSS plugin isAutoprefixer, which automatically generates the various browser-specific syntax for each CSS property as specified. In many ways thenumerous PostCSS pluginscould allow for the framework to replace Sass fully, but the downside is an unruly amount of dependencies with the looming possibility that any plugin could become an unmaintained or archived project. My personal approach is to limit myself to plugins maintained by the PostCSS group and only rely on other plugins that have an active user base.

      You might also like:A Beginner's Guide to Sass with Shopify — Part 1: Getting Started With Sass.

      Organization

      A key rule of maintaining a modern, scalable CSS codebase is using a consistent naming method and organizing preprocessor partial files effectively. CSS’s most important and most controversial feature is that every style is global. This feature gets at the core of how CSS works and is read by the browser. Unless it makes sense for your project to use the localized styles CSS-in-JS approaches can provide, then the reality is your CSS will be global. The best way to create ultra-specific CSS selectors is to use unique class selectors that follow a naming method.

      "Well-organized CSS architecture helps not only those currently working on writing CSS, but also anyone that comes to work on this code in the future, which could be the future you."

      除了技术原因CSS器官ization is helpful, there is a human argument too. Well-organized CSS architecture helps not only those currently working on writing CSS, but also anyone that comes to work on this code in the future, which could be the future you. If you’ve ever looked at your own code months or years later and had a hard time understanding what your wrote, these organizational methods will certainly be of use to you. This also means being empathetic toward everyone else that could potentially come along to work on your code. The better the organization, the better the position you put those future developers in.

      Naming methods

      It’s quite likely you’ve encountered a naming method approach when it comes to CSS selectors. Naming methods provide two important functions to CSS authors:

      1. Naming methods are for humans to read and clearly comprehend the purpose and use of a class selector.
      2. 命名方法提供一个高水平的特异性, so browsers can parse the CSS file and apply styles with minimal overwrites.

      There are several naming methods available, and you are, of course, free to create your own. A naming method isn’t a framework or library, but rather a convention and pattern that is applied to create clear and consistent class names. There are several existing naming methods, includingObject-Oriented CSS(OOCSS),Scalable and Modular Architecture for CSS(SMACSS), andBlock Element Modifier(BEM). The most popular of these three examples, and the method I personally use, is BEM.

      Nathan Rambeckwrote a great primer on getting started with BEM,BEM by Example, that I highly recommend. Despite its popularity, BEM is fraught with confusion. Every team I’ve worked with and taught BEM to has run into many of the same misunderstandings. After you’ve readBEM by Example, follow up with this article, which clears upcommon mistakes and frustrations when using BEM.

      File organization

      Following a naming convention is only part of the equation to a future-friendly CSS architecture. Another huge part is file organization. When using build tools like Sass to generate CSS files, it’s common and imperative that files be broken down into small pieces, often called “partials”. These partials are combined through a manifest file or build process to collect and concatenate them in to the final CSS output. How these file partials are organized can make a huge difference in the time it takes to track down where a feature resides.

      A good CSS file organization separates the code into related groups. For example, if you have a number of Sass variables that might be used throughout a project, it’s good to create a singular file full of variables. If you have many variables, it might be prudent to group those variables into other variable files, for example one for color variables and another for spacing variables. Likewise it’s good to create singular files that contain just Sass mixins or the CSS to create a specific feature of the website, like the site header or footer.

      You might also like:Live Reloading Shopify Themes: Sass Compilation with Theme Kit and Prepros.

      Inverted Triangle organization

      When it comes to organizing CSS in a prescribed manner, nothing has come close to the level of organizational craft as the Inverted Triangle method, or ITCSS. Manyothers have explained ITCSSin more thorough ways than I will. The premise of the approach is to work with the cascade feature of CSS. Browsers read CSS files from top to bottom, left to right. As the file is read, each selector and property manipulates the CSS Object Model, which in turn affects the Document Object Model.

      ITCSS is a concept developed by Harry Roberts and consists of seven parts, arranged in descending order: Settings, Tools, Generic, Elements, Objects, Components, and Trumps. It was designed as an approach to organize CSS in a way that started broad in specificity, such as element selectors, down to specific component classes for site features, and further down to classes that were intended to override, i.e. trump, any other classes.

      As Harry Roberts put it, “ITCSS takes CSS and writes it in a way that browsers and the design of the language can best utilize, which gives us far better scalability and maintainability than we'd get if we were to write CSS around how a person thinks.”

      Since ITCSS relies heavily on the cascade nature of Cascading Style Sheets, the term cascade is an important one to understand. A cascade is the flow of water downward often over rocky terrain. When we look at how we write CSS, we need to think of it as if we are traversing down a rock-laden water way. We can manage this feat best when we work with the current and be mindful of the rocks. When we try to go upstream or work against the current, our hard work begins to breakdown under the strain. The same goes for writing CSS: there is a current to follow down the cascade, and the ITCSS method is a map.

      css tools: inverted triangle
      The concept of the inverted triangle is a way to visualize the breadth of scope the Settings have versus the narrow scope the Trumps have (Image by Philip Zastrow based on the concept by Harry Roberts).

      If you’re interested in learning more about both BEM and ITCSS, I highly recommend taking a look atHarry Roberts’ articleon blending the two into what he calls BEMIT. The approach takes these two powerful techniques and makes them even more so by following BEM naming conventions informed by ITCSS organization.

      CSS namespacing

      Namespacing isthe next step in CSS organization后的命名约定。这是一个概念我只grasped in the last couple of years. The idea is to give a prefix to class names to provide additional context about the purpose of that class name. Namespacing—like BEM—is meant for humans, not computers. These are organizational methods that aid us in writing CSS that is efficient for both computers and humans to read.

      What I have personally found difficult, and I imagine I’m not the only one, is that the most prevalent method of namespacing in CSS is single character prefixes, e.g.c-forcomponent从倒三angle. I have personally found this difficult because it’s not quickly recognizable what thatc-prefix means. The context is lost on me and requires a key to navigate, which results in something else I have to remember. My preference, and what I have encouraged my teammates to adopt, is namespacing that provides more context by adding a couple more characters, for examplecmp-forcomponent. This has helped ease the comprehension of a class’s intent and aided in understanding its placement in the markup.

      You might also like:Getting Started With a CSS Grid Layout on Shopify.

      Smarter CSS

      CSS is a robust and capable platform for providing design instructions to web browsers. CSS tools like Sass and PostCSS along with naming conventions like BEM expand on this platform to provide ways for more experienced developers to use their skill sets. Web technologies are at their best when they provide avenues for anyone to create regardless of their skill level. For some, Sass is a way to take what they already know about programming and apply that to writing CSS. For others, Sass will level them up and start introducing them to programming concepts.

      From here there is plenty to explore and experiment with. In part two we’ll start taking the concepts discussed here and applying them to real-world scenarios.

      Grow your business with the Shopify Partner Program

      Whether you offer web design and development services or want to build apps for the Shopify App Store, the Shopify Partner Program will set you up for success. Join for free and access revenue share opportunities, developer preview environments, and educational resources.

      Sign up

      Grow your business with the Shopify Partner Program

      Learn more