Now that I’ve embraced React and Redux as my javascript framework of choice and have been building with it full time on the last few projects and interesting shift in the way I view CSS has begun.

Previously I would use a pretty minimal set of partials to bootstrap the styles of an application and I would grow that structure as new features were added on and new variables or mix-ins were required. With React I’m now seeing the vision of a component based architecture realized and this more global approach to styles feels like more of an anti-pattern. Through architecting these component based systems I’m still finding there are uses for some degree of global scope for things like grids for layout so to leverage the best of both worlds I’ve found CSS modules to provide a nice balance.

To demonstrate here is how my typical component structure is setup.

/Button
  /Button.js
  /index.js
  /Button.scss

Now typically I would pull in partials in the scss file and attempt to style for all of the permutations that I want to use my button for.

Button.scss

@import '_button.scss'

.Button {
  color: $btn-primary-color;
  background: $btn-primary-bg-color;
  ...
}

.Button--secondary {
  ...
}

This worked fairly well for a time but I found that there we lots of instances where I needed to override the default styles to work with a specific composition like in a modal footer or as part of a form. So I would stack a new class onto the component in more of a BEM approach using the getClassNames utility I shared in a previous post

Button.js

function getClasses (parentClasses) {
  const componentClasses = [
    'Button'
  ]
  if (parentClasses) {
    componentClasses.push(parentClasses)
  }
  return componentClasses.join(' ')
}


<Button className={ getClasses('Sign-Up__footer-button') } />

This worked well for a time but I found that I was writing a lot more CSS to cover the specific instances where I needed a set of minor tweaks for a composition than I should need but I didn’t want to create a big list of modifiers as that wouldn’t be maintainable. This approach also felt wrong as the majority of these styles weren’t re-usable which defeats the enhancements that originally brought me into preprocessors.

Another challenge was that now that I work in a dedicated javascript development role I collaborate with designers that manage the bulk of our CSS across projects so maintaining my own set of partials isn’t really feasible as the baselines need to be strictly versioned outside of my project.

To solve these challenges my team and I decided to adopt CSS modules. By using composition we are now able to maintain a large set of finely tuned variables and mix-ins in a separate project managed as an npm package without designers needing to be up to their eyeballs in React and I can focus on component design without risk of straying from our design standards. To demonstrate here is how I would build the button component.

Button.scss

.Button {
  composes: Button from '~/teamsnap-ui/src/_button.scss';
}

Button.js

import styles from './Button.scss'

<Button className={ styles.Button } />

There are still plenty of challenges to solve for such as how to theme a component for re-use across projects but I’m finding this outsourcing of the primary styles is working really well. I also get the benefit of collision projection BEM provides automatically due to the way these CSS module composed styles are converted into classes via javascript .Form-Button__as34sdf.

I’ve found there are still a few use cases for more global CSS such as grid classes you want to just apply to a component but I’m confident that with time we can find elegant solutions to maintain those as components as well. I hope this helps you find new ways to leverage component architecture and if you have any feedback or suggestions be sure to hit me up on Twitter. Happy Coding.

As I’ve worked with several different teams over the years I’ve found documentation to be a bit of a hot button topic. Some feel over documentation is the only way to professionally deliver work and some prefer to simply write “self-documenting” code. I’ve sat through multiple debates and have been part to many a code review where these two mindsets have caused quite a stir.

Premise

On a recent fairly large application build I decided to test some theories around documentation with Sass. I wanted to attempt a documentation driven approach which I define as:

All code that is intended for re-use or extensibility within a library or project should have documentation written up-front or in parallel instead of it being added after the fact.

This may at first just appear to be a pedantic argument, but I wanted to research and possibly prove a couple of hypotheses through this approach.

1.) The project at the end wouldn’t lack documentation like so many other great projects do and if the documentation efforts had fallen behind it would be less effort to back fill.

2.) Code quality would increase as there was more thought put into the solution at the time of authorship.

In my opinion CSS is a fairly simple language with a long history of hacks. I find its very easy and far to common to just write more code rather than think through problems up front and write well thought out modular solutions. Also documentation as a practice is pretty rare in CSS as a whole unless you are viewing the source for a popular public framework or library.

Risks

Alongside these hopeful outcomes I also theorized a couple potential side-effects of taking this approach.

1.) Developers velocity would decrease as more thought would be needed during authoring and this might disrupt a typical workflow.

2.) Code bloat. I wondered if writing docs upfront would influence a developer into thinking every line of CSS has to be modular and re-usable.

I feel these risks have to be weighted differently depending on the project. In my test case above, we had plenty of runway to work through some early prototypes and think of systems to use in our css. These fairly complex systems necessitated a comprehensive set of accompanying documentation that other engineers could ingest for feature development. If I had a smaller site or project I doubt I would take such a stern approach to being document driven.

Tools

KSS is the tool I decided to use for documentation. It had some notable use cases and pretty decent documentation even if it only provided ruby references. I also utilized a gulp plugin to automate this step into our existing build pipeline. We also created our own theme for our documentation and incorporated angular and google material as both of those libraries are used in the project and they were needed as dependencies in order to properly represent our apps components.

Conclusion

If I told you this experiment went off without a hitch I would be lying. We did end up having a much larger and more comprehensive set of documentation, but when deadlines loomed we loosened our convictions to maintain them. We ended up having to backfill documentation and do several rounds of refactoring to get our Sass components and docs up to date after major deadline pushes with new feature development. The documentation did however prove to be a useful resource to more team members that were more focused on data and application development with less focus on UI. Overall I feel that for this strategy to be successful it needs to be established as a core principle for each team and there really needs to be buy in from the whole team to ensure success.

I love approaching projects from a modular, componentized approach and commonly am looking for new tools or techniques across languages to facilitate this methodology.

Today I was reading an interesting post on making css typography more modular and came across a thought provoking statement on the authors rationale on using a css reset over something like Normalize.

The other reason to start with a fuller reset is that starting from zero allows you to layer on styles without worrying about turning off other styles. Read that one more time. Anytime you have to turn off styles in multiple places in your stylesheets your are spreading the knowledge of those styles throughout your stylesheet instead of having them in only one place.

This is interesting for me since a couple years back I switched from using Eric Meyers reset to using Normalize so I could focus more on the unique UI components of an application from a sensible baseline instead of having to start from ground zero.

Reflecting on some of these projects now however, I can 100% see how that mindset / approach can totally backfire and make truly modular code difficult. Typically this has manifested for me any time I needed to refactor a component from being view / feature specific to something more useful to the application globally. I seem to find that the cascade from parent components or default styles are coupling the component and thus quite a bit of css needs to be refactored.

On my next project I think I’ll try switching back to a reset and see if this assists in better flexibility.

So recently I was working on an angular directive that produced a content card and each of them needed a unique accent color. Each of these cards are produced through an ng-repeat as a result of an api response that was fairly limited in data / context. Essentially all I had to identify each card was a single letter that was used on each card.

Usually in this situation I would just manually write six disctinct classes since there was such a small number of variants but lately I’ve been seeing some fun applications of sass maps and functions so I wanted to give them a shot. Below is what I ended up with.

$card_colors: (
  'r': $blue,
  'i': $green,
  'a': $mustard,
  's': $burnt_orange,
  'e': $spray_blue,
  'c': $burnt_sienna_red
);

@function get-color($color_code: r) {
  @return map-get($card_colors, $color_code);
}

@each $background, $color_code in $card_colors {
  .code_background-#{$background} {
    background-color: get-color($background);
  }
}

Overall I’m pretty pleased with the power of this approach but I do worry a little about how readable and maintainable this approach would be for a developer that comes behind me.

I also at some point need to do some performance evaluations as traditionally sass maps haven’t been recommended in production due to performance. Thoughts?

So for the past few months I have been using Sass for all of my projects. I’ve been using Bourbon and Bourbon Neat as part of my workflow but recently have been working to implement rem measurements for my typography to assist in font scaling for responsive builds. This was a bit daunting at first after I read about the calculation for rems as I was already used to being spoiled by Bourbon’s em() function so I whipped up a function to do the conversion for me.

// calculate rem based on a pixel value
@function rem($value, $fontbase: 10) {
  @return($value / $fontbase) * 1.0rem;
}

.rem_test {
  font-size: rem(40); // 40px == 4rem
}

Hope you find this helpful.

So if you haven’t jumped into bootstrap to speed up front end development or at least explored it you need to, and hopefully this writeup taken from some of my successes and failures will help jumpstart you into using it effectively as
a front end scaffold.

First we need to understand that Bootstrap is a framework..

One of my first mistakes was in not really understanding what this means and customizing its core directly. This mistake has caused numerous problems like being stuck with an older version and working way harder to override its css output :(

After the first couple of projects I found that the only way to use it effectively is to build off of it and not customize its core files directly. This concept is similar to other platforms and libraries I use { jQuery or WordPress } but it didn’t occur to me immediately since it was a front end framework and the early documentation guided users to work off of the variables to customize it. This caused me plenty of problems until I found the below approach.

Setup

Download the full source from Github { the LESS version }

https://github.com/twitter/bootstrap This is the full core of the framework. It will take some learning if your not already using LESS but it shows how the features are truly built. If you haven’t already viewed bootstrap like this take some time and examine the files and learn which features are created through each file, there are quite a few and learning where they are defined will help later when you want to build off of them or over-ride their look and feel.

Get the right tools

I use a compiler which took some time to getting used to as a front end guy who’s previous experience with compilers was Dev C++ in an intro CS class. I’ve come to find with a little flexibility in my workflow it speeds things up and can help with debugging as I’m adapting to using LESS instead of just CSS. I currently use CodeKit which offers some cool js and framework support. It is a paid app so if your just getting started you might want to try some of the free options { LESS for Mac, WinLess ( ironic ), Simpless, or Crunch. }

Set up your development project

Recently at WordCamp here in St. Louis I discussed theme development best practices and one of the concepts I covered was abstraction. The concept holds true in the method I use to work with bootstrap which I find to work really well. I start with a basic project folder for the site name or project I’m working on and create the basic folder structure for the types of files I will be using. I also add a folder called bootstrap to contain the frameworks less files.

Now I copy over the files from bootstrap that I downloaded from Github into the appropriate directories minus the tests folders that were used in development. Now I have a clean folder structure with some basic assets to start using on my project.

Getting started

Now that you have a basic site structure lets set up our compiler with some resources and instructions on how to produce our styles. First inside of our less folder lets create some .less files to tell the compiler what we are working with. I start with a

  • style.less { the master file },
  • layout.less { general layout },
  • theme.less { colors, buttons, etc }
  • typography.less { for headings and type faces }
  • misc.less for mixins and utility classes.

Once these files are created open your style.less file and add the following lines.

/* my new bootstrap site */

@import "../bootstrap/bootstrap.less";
@import "../bootstrap/responsive.less";

// import your unique less files as you build

@import "layout.less";
@import "theme.less";
@import "typography.less";
@import "misc.less"  // mixins etc

Once you have created these files and this structure you can open your compiler of choice and add your new project. In CodeKit you simply click the (+) plus sign and browse for your site folder. Once you have chosen this lets modify the compiler behavior.

Basically we want to make sure it is detecting the import statements and that it is only compiling the single style.less file. Also if it doesn’t automatically set the output path for the compiled css you will want to right click and tell it to use /css/style.css. Now we can get started on building our new site with less and the power of bootstrap so if your not already confused read on.

File Strategy

I mentioned before that one of the key things I’ve learned as a developer is abstraction. This concept is constantly at the back of my mind when I’m working on a project because I find its the best way to build readable clean code that someone else may have to work on down the road after I’m finished working on a project. When I set up my less folder with those basic files in the previous step its just a starting point. As I get further into a site I will create several more less files and import them into the style.less file so they are compiled into the final css. This maintains clean easy pieces in my code that are easy to digest.

I also heavily comment using less comments // as they don’t end up in the css and are a courteous way to document my train of thought as I’m working on a layout.

The key thing is to not be afraid of files.

With this method and less they are compiled into one css file so your not adding a bunch of extra http calls and damaging your sites load time by keeping everything broken out and readable. You can even take optimization a step further when your ready to put your site into production and only import the bootstrap files that actually pertain to your design.

Wait.. what ?

Yes. If you open the bootstrap.less file from the framework you’ll see they are doing the same thing with import statements so you can lower the end size of your css file by only pulling what you need!

Closing

This has taken a couple of months for me to refine and get comfortable with but now I’m finally starting to see the benefits as I work with a team of developers on larger projects. This organization lets us minimize development time and makes our code easier to understand without lots of instruction and I hope it helps you on your development projects in the future. If you see improvements that can be made I’d love to hear your feedback or findings while you experiment.

Happy coding.