Jason Reece - Big Nerd Ranch Tue, 19 Oct 2021 17:46:25 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 PostCSS: Life after Sass https://bignerdranch.com/blog/postcss-life-after-sass/ https://bignerdranch.com/blog/postcss-life-after-sass/#respond Sun, 25 Jun 2017 11:08:20 +0000 https://nerdranchighq.wpengine.com/blog/postcss-life-after-sass/ We've begun to use PostCSS plugins in almost all of our web projects to lint our CSS, support variables and mixins, transpile future CSS syntax, inline images and more. So we've started to ask the question: If PostCSS is always going to be a project dependency, do we still need to use Sass in our projects?

The post PostCSS: Life after Sass appeared first on Big Nerd Ranch.

]]>

We have begun to use PostCSS plugins in almost all of our web projects to lint our CSS, support variables and mixins, transpile future CSS syntax, inline images and more. For example, we’ve been using Autoprefixer to add our vendor prefixes for us, and stylelint for linting our stylesheets.

So we’ve started to ask the question: If PostCSS is always going to be a project dependency, do we still need to use Sass in our projects?

As it turns out, we can actually get most of the functionality of Sass from a single PostCSS plugin.

Introducing PreCSS

PreCSS is a tool that allows you to use Sass-like markup in your CSS files. It lets you enjoy a familiar syntax with variables, mixins, conditionals and other goodies.

PreCSS is actually just made up of a number of smaller PostCSS plugins. You could simply use each of the individual plugins, but then you’d need to manage the order that the plugins process your stylesheets, so it is much easier to use PreCSS.

PreCSS alone will give us most of what we’d need to replace Sass, but there are plenty of additional PostCSS plugins to choose from. Let’s check out a few more!

cssnext

cssnext is a PostCSS plugin that helps you to use the latest CSS syntax today. It transforms new CSS specs into more compatible CSS so you don’t need to wait for browser support.

cssnext provides a long list of features.

Here’s an example using the custom properties & var() features.

// out with the old
$color: blue;

.selector {
  color: $color;
}

// in with the new
:root {
  --color: blue;
}

.selector {
  color: var(--color);
}

Stylelint

Stylelint is a mighty, modern CSS linter that helps you enforce consistent conventions and avoid errors in your stylesheets.

Stylelint’s linting rules are completely configurable. You can write a completely custom config, but it is common practice to start with the stylelint-config-standard, and then override individual rules as required by the needs of your project.

Stylelint will gently remind you when you make mistakes.

Bad

Or high five you when you get it right!

Good

cssnano

cssnano takes your nicely formatted CSS and runs it through many focused optimisations, ensuring that the final result is as small as possible for a production environment.

cssnano will perform a number of useful optimizations on your stylesheets including minification, adding vendor prefixes and compressing inline SVG definitions.

The PostCSS CLI

PostCSS doesn’t do anything by itself, it only processes an array of PostCSS plugins. We can use any of the popular build tools like Webpack, Gulp or Grunt to power PostCSS. For this simple example, we are just going to use an npm script.

So we’ll need to globally install the PostCSS CLI.

npm install -g postcss-cli

Let’s Build Something

Let’s set up a simple project so we can test it out!

First let’s create a new project, and create a new package.json file.

mkdir postcss-example && cd postcss-example && npm init

Next let’s install all of our PostCSS plugins, and save them to our package.json file.

npm install postcss-cli stylelint stylelint-config-standard postcss-cssnext precss postcss-cssnext cssnano --save-dev

Then we’ll add the following to the scripts section of the package.json file.

"scripts": {
  "styles": "postcss input.css --config postcss.config.js --output output.min.css --watch"
},

Here we are telling PostCSS to --watch for changes to the input.css file. When a change occurs, we want PostCSS to look at our --config file (we’ll be creating that shortly) and based off of that config, write to our output.min.css file.

So, let’s create our postcss.config.js file.

touch postcss.config.js

Our config should look like this:

module.exports = () => ({
  plugins: {
    'stylelint': {
      "extends": "stylelint-config-standard",
      "rules": {
        "max-empty-lines": 2
      }
    },
    'precss': {},
    'postcss-cssnext': {},
    'cssnano': {
      'autoprefixer': false
    }
  }
});

There are many more config options available, but for our simple example, this will get the job done. (If you want to add additional plugins, just remember that the order that the plugins are entered into the config matters.)

So, here we are linting, then compiling our Sass(like) syntaxes, then our cssnext syntaxes, then finally we are minifying with cssnano.

For our stylelint plugin, we are telling stylelint to extend the default linting rules from the stylelint-config-standard package, and then to override the max-empty-lines rule with the rules object. Here we are setting the max number of empty lines to 2.

You’ll also notice that we are setting autoprefixer to false inside of the cssnano object. Autoprefixer is actually built into both the cssnext and cssnano plugins. We don’t want to run Autoprefixer twice, so make sure to turn it off in cssnano.

Ok, now that we’ve finally gotten everything into place, let’s test this thing out!

Create a new stylesheet.

touch input.css

Start watching for changes.

npm run styles

Now, when we make edits to input.css, we should be seeing a minified, compiled version in output.min.css.

If you want to see your changes in the browser, you can create a simple index.html file and link to the output.min.css file.

Be sure to not only test out the PreCSS syntax, but also to take a look at cssnext!

Some Takeaways

I really do like the idea of moving away from using Sass. In the ever-expanding world of front-end development, it is always a good feeling when I can remove dependencies from my projects. I especially like that PostCSS allows developers to write in a ‘future-proof’ syntax.

However, in my brief experimentation, I did notice a few issues.

The biggest hurdle was the learning curve that the new syntax introduces. It isn’t necessarily complicated or hard to understand, but I did myself seeking out the documentation quite a bit. For example, developers familiar with Sass will expect a mixin to look something like this:

// defining the mixin
@mixin thing($bg-color, $color) {
    background: $bg-color;
    color: $color;
}

// using the mixin
.selector {
    @include thing(red, blue);
}

A PreCSS mixin looks like this:

// defining the mixin
@define-mixin thing $bg-color, $color {
  background: $bg-color;
  color: $color;
}

// using the mixin
.selector {
  @mixin thing red, blue;
}

Again, one of the main goals of PreCSS is to provide a W3C friendly future-syntax. So becoming familiar with the syntax now isn’t necessarily a bad thing.

Another minor disappointment from PreCSS is a lack of custom functions. In my Sass projects, I often write custom functions to handle repetitive tasks for me.

For example, I might write something like this:

// - - span-columns - - spans x number of columns
@function span-columns($columns) {
  @return (1068 / 12 * $columns * 1px);
}

.avatar {
    width: span-columns(3); // width: 267px;
}

To be fair, this functionality doesn’t come built into PreCSS, but you can add custom functions using the postcss-functions plugin.

Overall, I really enjoyed using PostCSS. I have no doubt that PostCSS will be in my workflow for quite some time!

Want to learn more? This blog post barely scratches the surface. There are so many useful plugins. And if you’re in Atlanta, keep an eye out for an upcoming talk at the Atlanta Sass Meetup.

The post PostCSS: Life after Sass appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/postcss-life-after-sass/feed/ 0
Sass From Zero to Sixty https://bignerdranch.com/blog/sass-from-zero-to-sixty/ https://bignerdranch.com/blog/sass-from-zero-to-sixty/#respond Tue, 10 Nov 2015 11:00:00 +0000 https://nerdranchighq.wpengine.com/blog/sass-from-zero-to-sixty/ This post will get new Sass users up and running, and help more seasoned users shift their sassiness into the fast lane.

The post Sass From Zero to Sixty appeared first on Big Nerd Ranch.

]]>

Sass has been around since 2006, and is quite popular. However, since organizing the ATL Sass Meetup a year ago, I’ve met plenty of people who have heard about the language, but aren’t exactly sure where to start. This post is designed not only to help new users get their projects up and running, but it will help more seasoned users shift their sassiness into the fast lane.

What is Sass?

Sass is a stylesheet language that compiles into CSS, adding features like variables, mixins and iteration that do not yet exist in the CSS language. Sass has two syntaxes. (For this post, we’ll be writing in the .scss syntax.)

Installing Sass

Our first step for brand-new users will be to get Sass installed. Open up the command line, and run:

gem install sass

If that fails, try running:

sudo gem install sass

Success? Check the version:

sass -v

Still having trouble? Look here.

Compiling Sass

Now that we’ve got Sass installed, we’ll need to look at how we want to compile our Sass code into CSS.

Sass can be compiled via the command line, or with a desktop application like Codekit, Prepros or Scout.

There are also a number of task runners that will compile your Sass for you like Gulp, Grunt or Broccoli.

For the remainder of this post, we’ll be using Gulp to compile our Sass (and do other CSS related things that will make our lives easier).

We are going to use Gulp to:

  • Start our local server
  • Watch for changes to our Sass files
  • Check for errors
  • Compile our Sass
  • Add CSS3 vendor prefixes
  • Add minification
  • Write our CSS file
  • Reload the browser

Installing Gulp.js

First, make sure that Node is installed:

node -v

If you need to install Node, you can download it here.

Now install Gulp.js:

npm install -g gulp

If that fails, try using sudo:

sudo npm install -g gulp

Now we are ready to set up a new project.

Download the Template

First, download the starter template. This template contains:

  • package.json – a list of npm packages that we will install
  • gulpfile.js – a list of tasks that we want Gulp to run for us
  • application.scss – our Sass file
  • index.html – our hello world web page

Now we just need to install all of the npm packages listed in our package.json file.

In the command line, navigate to the root of the starter template, and run:

npm install

That should have created a node_modules folder with all of the npm packages listed in the package.json file.

We’ve just installed:

Now we just need to run:

gulp

This will run our default task. This task starts up our server local server, opens the browser and begins watching our Sass file for any changes.

Let’s trigger the styles task by making some edits in the application.scss file.

body {
  background: red;
}

When there is a change in our Sass file, the styles task will:

  • check our Sass for errors
  • compile our Sass
  • add the needed vendor prefixes
  • minify our code

Finally, the reload task will reload our browser.

For a look at exactly how this is set up, check out the project’s gulpfile.js. Breaking down the gulpfile.js is outside of the scope of this post, but if you’d like a good tutorial, check out Todd Gandee’s Journey into Gulp post.

Some Additional Gulp Tasks

A few other Gulp tasks that you might consider adding into your build process are:

Project Organization with Partials

We’ve got a pretty good build process set up, but instead of having one giant Sass file, lets look at how we can better organize our code using Sass partials.

When Sass compiles, it will create a matching CSS file for any file with a .scss or .sass extension. However, if we prefix our file names with an underscore, Sass will not create a matching CSS file.

So, application.scss will get a matching application.css file, but _my-partial-file.scss will not.

We can use this technique to create an organizational structure for our project. We’ll break our styles up into partial files, and then use @import to bring all of the partial files into the main application.scss file.

// in the application.scss file
@import 'my-partial-file-one';
@import 'my-partial-file-two';
// etc

css-burrito

So, what should our structure look like?

I have written an open source Sass Template called css-burrito that will provide a very scalable Sass structure. In addition, it will automate a few tasks for us like adding and removing partial files.

The template contains three directories and an application.scss file to @import all of the partial files.

libs/
  _library-variable-overrides.scss
  _normalize.scss

global/
  _settings.scss
  _utilities.scss
  _base.scss
  _layout.scss
  _skin.scss
  _typography.scss

modules/
  _modules.scss

application.scss

Libs

The libs directory will house all third-party library code. Add libraries like Bootstrap, Foundation or Bourbon here. By default, this folder contains:

  • _library-variable-overrides.scss – override any third party library variables in this file.
  • _normalize.scssNormalize v3.0.2

Global

The global directory is where we will keep all of the utility code that will be used across the entire project. It should be organized as follows:

  • _settings.scss – global variables and maps
  • _utilities.scss – global placeholders, extends, mixins, functions and utility classes
  • _base.scss – global defaults for base level tags like <body> or <p>
  • _layout.scss – global layout styles like margin, padding or floats
  • _skin.scss – global skin styles like gradients, colors and box-shadows
  • _typography.scss – global typography classes

Modules

The modules directory will ultimately contain the majority of the code in your project. You’ll add new modules as needed based on the design. This directory also contains a _modules.scss file, to @import all of the other modules into the application.scss file.

css-burrito Comes with Superpowers!

If you want css-burrito to create files and @import them for you, you’ll need to install it as a global npm package.

npm install -g css-burrito

Once installed, you can quickly add a new instance of the css-burrito template by navigating to the root of the project and running:

burrito -n [folder-name] [file-name] [path-to-sass-directory]

This will create a new instance of the css-burrito template, and a css-burrito-config.json file.

Once the config has been created, you can update the modules directory in a number of ways.

Add new module partials to the modules directory:

burrito -m (file-name[s])

Remove module partials from the modules directory:

burrito -r (file-name[s])

And list the partials in the modules directory:

burrito -l

css-burrito Customization

If you want to rename any of the files or partials, or edit the structure of the template itself, you can make edits to the css-burrito-config.json file. Once the config edits are in place you can generate a customized version of the template by running:

burrito -g

Let’s Put This all Together!

Ok, so now we have an awesome build process set up with Gulp, and we know how we want to organize our files.

Let’s create a new project by downloading the starter template.

The gulpfile.js has been updated to watch our new project.

Sassy Patterns

Now that we’re ready, we can finally begin to write some code!

Lets take a look at some useful patterns.

Sass Maps

I use Sass maps in all of my projects for two reasons. First, it limits the number of global variable names in the project, and second, they can be iterated over with an @each loop.

To get something out of a map, you’ll use the built in map-get() function. This takes two arguments, the name of the map and the key that you want to get out.

$colors: (
  'primary': #bada55,
  'secondary': #c0ffee,
  'tertiary': #de1e7e
);

.thing-that-needs-some-color {
  background: map-get($colors, 'primary');
  color: map-get($colors, 'secondary');
  border: 1px solid map-get($colors, 'tertiary');
}

Play with this gist on SassMeister.

Custom Functions

I am not a big fan of typing map-get() everytime I want to get something out of a map. Instead, I like to create a function for each map to get things out for me.

Let’s create our own custom function to use with the $colors map. This new function uses the built-in Sass function map-has-key(), which takes in a map and a key and returns true or false depending on if the key exists.

When we call the colors function, we pass in a key—in this case, the color that we want to get out. If the key exists, our function will run a map-get() for us. Otherwise, we log a warning and exit out of the function.

$colors: (
  'primary': #bada55,
  'secondary': #c0ffee,
  'tertiary': #de1e7e
);

// grab colors from $colors map
@function color($key) {
  @if map-has-key($colors, $key) {
    @return map-get($colors, $key);
  }
  @warn "Unknown `#{$key}` in $colors.";
  @return null;
}

// lets call the function 3 times
.thing-that-needs-some-color {
  background: color('primary');
  color: color('secondary');
  border: 1px solid color('tertiary');
}

Play with this gist on SassMeister.

@each Loops

Finally, we can iterate over maps using an @each loop. Here, we are looping through the colors map, getting the $color-name and $color-hex, and creating a ruleset with that data. We need to use interpolation to add the $color-name.

$colors: (
  'primary': #bada55,
  'secondary': #c0ffee,
  'tertiary': #de1e7e
);

// loop through the colors map,
// get the key and value,
// and create a ruleset with the data
@each $key, $value in $colors {
  .t-color-#{$key}{
    color: $value;
  }
}

Play with this gist on SassMeister.

Sassy Resources

All right! We’ve learned how to install and compile our Sass, set up a Gulp task to process our styles, create a file structure, and have seen a number of useful patterns. We are now cruising along smoothly at 60 mph.

However, it turns out that on this highway, there is no speed limit!

There are tons of really useful @mixins and @functions out there, and lots of people doing amazing things with Sass.

Sass is a powerful language, so it is also very easy to crash and burn. I recommend using tools like Sassmeister to keep an eye on the CSS that you are outputting.

In addition, take a look at the Sass Guidelines to make sure that you are writing sane, maintainable and scalable Sass code.

Want to learn more? Join us at the next ATL Sass Meetup.

The post Sass From Zero to Sixty appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/sass-from-zero-to-sixty/feed/ 0
css-burrito: An Open-Source Organizational Sass Template https://bignerdranch.com/blog/css-burrito-an-open-source-organizational-sass-template/ https://bignerdranch.com/blog/css-burrito-an-open-source-organizational-sass-template/#respond Tue, 20 Aug 2013 18:02:48 +0000 https://nerdranchighq.wpengine.com/blog/css-burrito-an-open-source-organizational-sass-template/

How OCD is your CSS? Are you following object-oriented conventions? Do you adhere to a strict style guide? Do you have a hard time sleeping if your properties haven’t been alphabetized, or if they aren’t organized into sections like “Positioning” and “Box Model”?

The post css-burrito: An Open-Source Organizational Sass Template appeared first on Big Nerd Ranch.

]]>

How OCD is your CSS? Are you following object-oriented conventions? Do you adhere to a strict style guide? Do you have a hard time sleeping if your properties haven’t been alphabetized, or if they aren’t organized into sections like “Positioning” and “Box Model”?

If so, you are a perfect candidate for using a css template like css-burrito.

To understand why you would want to use this template, it is a great idea to familiarize yourself with the following css architectures:

OOCSS – Object-Oriented CSS

  • Separate structure and skin – Structure properties like width and height should be separated from skin properties like background and border.

  • Separate content from container – Content modules like buttons and lists should not be dependent on their parent containers.

SMACSS – Scalable and Modular Architecture for CSS

  • Increase the semantic value of HTML and content.

  • Decrease the expectation of a specific HTML structure.

  • Organize your css files into sections like base rules, layout rules and modules so that the styling will be flexible and easily maintainable.

MVCSS – A Sass-based CSS architecture and style guide.

Ok, now that you’re familiar with those concepts, are you hungry for some burrito?

What is css-burrito?

css-burrito is a Sass template to help integrate suggested best practices into any project.

To use this template, just delete your current stylesheets directory (or whatever the folder that houses your CSS files is named), and replace it with this one. Then update your path on your projects index page if necessary.

Note for Rails Users:
Any new .scss files that are created by generating Rails controls will not be used, and can be deleted.

What is in this burrito?

css-burrito has four main ingredients.

1. Application.css.scss

  • This section serves three purposes.

  • It imports all of the files from the Libs, Core and Module sections.

  • It has an Inbox section where developers that don’t usually work on the project can leave temporary files that are easily seen by the maintainers of the project.

  • It has a Shame section for quick fixes, hacks, and other questionable techniques. Be sure to fix them later.

2. Libs

This section will house CSS libraries like Normalize, Compass, Bootstrap, Foundation or Pure.

It also contains a library-variable-overrides file. Any overrides to Bootstrap or other library variables should be made in this file to prevent unnecessary overwriting.

Normalize is included in the libs folder by default.

3. Core components

There are five core components:

  • Settings – @font-face and global variables.

  • Helpers – Extends, Functions, Mixins.

  • Base – Base-level tags (body, p, etc.).

  • Typography – Base-level typography (colors, fonts).

  • Layouts – Base-level layout (margin, padding, sizing).

4. Modules

Any unit of style that can be found across multiple pages (Buttons, Navigations, Modals).

Most of your styles should be found here.

Lets talk about States

Inside the layouts file and in the example-module file, there is a section for styling states.

  • States are styles that override all other styles, usually via JavaScript.

  • States are generally applied to the same element as a layout rule, or to the same element as a base module.

  • An example would be a navigation drop down, or a message that displays a success or error state.

  • State classnames should be written as a boolean. For example, .is-collapsed or is-error.

  • When state rules are added to specific modules, the module name should be included in the classname. For example, an active tab state could be written as .is-tab-active.

Wrapping it all together

This template should feel intuitive and easy to use. The goal is to keep everything organized so that large projects will scale nicely without duplicating code, or having unnecessary increases in specificity.

See something that could be improved? Let us know in the comments.

The post css-burrito: An Open-Source Organizational Sass Template appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/css-burrito-an-open-source-organizational-sass-template/feed/ 0