There are a few of these posts floating around at the moment and I loved the idea. A great way to share real world approaches, code and methods to CSS. So below is how DesignyourCode does CSS.

I use SCSS

I format in a certain way

Mainly because I am a bit OCD on looks, some of the things I do have absolutely no impact on the code, but by being controlling in this way, I keep track of my code better and think about what I am doing more.

.box {
    float: left;
    height: 100%;
    margin: 0 10px 0 0;
    width: 33.33%;
    @include border-top-radius(6px);
    @include border-bottom-radius(6px);
    @include transition(all .3s ease-in-out);

    .inner {
        background: $purple;
        color: $white;
        display: inline-block;
        width: 100%;
    }
}
  1. You can see here, I use my selector on one line. A space between the selector and the opening brace.
  2. Each property is on a separate line, with the definition indented by 4 spaces (NOT TABS). The colon follows immediately, with a space and then my value, ended by a semi-colon on every line – CSS is forgiving and doesn’t need a semi-colon on the last property, but often the gulp compiler doesn’t like it, so a good habit to get into is closing your code properly.
  3. The closing curly brace is on it’s own line at the end and is inline with the selector.
  4. Zero values have no units assigned. So 0px is wrong.
  5. Personal preference: I organise my properties into alphabetical order. This sort of order has no impact on code performance or operation. It simply helps me find what I am looking for a micro-second quicker. For example I know width will be near the bottom, and border will be near the top.
  6. I keep my @includes last. This again has no impact on code function, I just like to group things neatly. You’ll also notice my @includes in length order. Shortest first, longest last…see told you I had OCD on this stuff.
  7. Lastly, child element properties follow the same format as above, but I always add a space between my last parent value and the child block.

Organising files
Every developer knows it is a good idea to keep your code in small chunks that are easily manageable. With the help of gulp this is made very easy to do with my SCSS files.

One thing I do in every project is have an app.scss file. This file is the file that will get compile by gulp into my app.css file that the project will actually use, think of it as a table of contents for the rest of my code.

My app file for DesignyourCode looks like this:

@import 'bourbon/bourbon';

@import 'normalize';
@import 'mixins';
@import 'settings';
@import 'prism';
@import 'wysiwyg';
@import 'global';

@import 'layout/layout';
@import 'layout/sections';

@import 'singletons/buttons';
@import 'singletons/objects';
@import 'singletons/pagination';
@import 'singletons/forms';
@import 'singletons/commenting';

The next thing I do is split my partials into groups. This helps me create an unwritten guide on where items should go. For example, the top block contains external files that should be declared first. For example bourbon and neat are common items I use.

Next are globally defined items for the site (this sits in the top level of my styles folder. They are then organised by the natural order they should be called in. For example normalising and resetting the browsers comes before defining fonts and colours.

My SCSS variables, fonts, colours and so on goes in settings. This makes a site or app feel more like a system with configurable options. Especially when using something like Bourbon Neat, where you might set global layout widths and gutter sizes.

Next are layout related items. This is where I create my layout and sections. The more generic these can be, the more flexible your layout is and the more control you have over it. Another term I use often is modules. This works particularly well for sites that have a lot of boxes and sections. This would be another folder.

Lastly I have singletons. This is where I define individual elements and their customising. For example my buttons are in their own partial. In it’s simplest format, it looks like this:

%button {
    outline: none;
    border: none;
    cursor: pointer;
    display: inline-block;
    margin-right: 6px;
    padding: 8px 18px;
    text-align: center;
    vertical-align:middle;
    width: auto;
    @include transition(all .3s ease-in-out);
}

.btn {
    @extend %button;

    &.right {
        float: right;
    }

    &.btn-purple {
        background: $purple;
        color: $white;
    }

    &.btn-blue {
        background: $blue;
        color: $white;
    }
}

Setting up my partial this way has multiple benefits:

  1. I can extend my buttons easily. By using %button, I create a way where I can then extend it into any button I like quickly, but could also use .button without any problem. If I had used .button as my extend base then I could run into issues.
  2. Using the extend feature as the base of my .btn I can then create classes to suit my mark up situation. For example I can use class="btn btn-blue" or I can use class="btn-blue". The following works for .btn-blue format.
%button {
    background: $black;
    color: $white;
    outline: none;
    border: none;
    cursor: pointer;
    display: inline-block;
    margin-right: 6px;
    padding: 8px 18px;
    text-align: center;
    vertical-align:middle;
    width: auto;
    @include transition(all .3s ease-in-out);
}

.btn {
    @extend %button;

    &-blue {
        @extend %button;
        background: $blue;
    }
}

This method allows me to keep my classes names compact which is nice for markup. You just have to remember to include the @extend in the .btn, and the &-modifier. This also means you can use .btn on its own in your markup.

Having a base class will allow you to scaffold a site quickly. I tend to use the same preset SCSS files across most of my projects. Then I add modifiers to adjust the styles accordingly. Think a seriously slim bootstrap and overrides.

I use gulp to compile

I use gulp for a lot of functionality when building sites; including live reloading the browser when I make a change, concatenating scripts and especially for compiling my SCSS into a production ready css file.

You can find an example of a gulpfile I use often in my gulp-boilerplate project.

Things to note:

  1. I use gulp-plumber to stop gulp from crashing if there is a SCSS error.
  2. I use gulp-notify to send desktop notifications to me if there is a SCSS error. This is so I don’t keep trying to hit save, see no changes in the browser and going back to my SCSS and making more changes. The notification is helping if my command window is minimised or on another screen.
  3. I use gulp-sass to compress my SCSS into minified code. This means the files size of the css file I used on production is a single file which is as small as possible.

Why Gulp and not Grunt

Simple. Gulp is faster.
In my experience, gulp has always been faster at compiling SCSS that Grunt. I am also now at a point where gulp is baked in to so many projects that I would have to experience something pretty fatal with gulp to make me want to switch.

I sort of use OOCSS

…but really I just using classes the way they were intended. Below is an example of a common way of creating and styling a box.

<section class="box">
    <figure>
        <img src="http://placingbad.com/300/200" />
    </figure>
    <h2>This is a heading</h2>
    <p>Lorem ipsum goes here...</p>
</section>

And the SCSS that goes with this:

.box {
    float: left;
    width: 33.33%;
    @include border-top-radius(6px);
    @include border-bottom-radius(6px);
    @include transition(all .3s ease-in-out);

    figure {
        margin-bottom: 10px;

        img {
            height: auto;
            width: 100%;
        }
    }

    h2 {
        font-weight: bold;
        text-transform: uppercase;
    }

    p {
        margin-bottom: 10px;
    }
}

Now this works for the majority of the title, but it can be limiting if a project needs to scale. So I will generally add a small number of class to allow me scale this at a later date. Below is the improved version:

<section class="box third left rounded">
    <figure class="gap-bottom">
        <img class="responsive-img" src="http://placingbad.com/300/200" />
    </figure>
    <h2 class="title uppercase">
        <strong>This is a heading</strong>
    </h2>
    <p class="gap-bottom">Lorem ipsum goes here...</p>
</section>

And the SCSS that goes with this:

// styles/layouts/layout.scss
.left {
    float: left;
}

.third {
    width: 33.33%;
}

// styles/global.scss
.rounded {
    @include border-top-radius(6px);
    @include border-bottom-radius(6px);
}

.gap-bottom {
    margin-bottom: 10px;
}

.responsive-img {
    height: auto;
    width: 100%;
}

.uppercase {
    text-transform: uppercase;
}

You can now see that I have removed the need for styling that is specific to that box. I have made those properties global. So they can move from say my modules partial and be put into global and layout. This now means I have freed my module partial up to have specific code for the box itself, like colours or alternate specific layouts. This means my modules file may become:

// styles/modules/box.scss
%box {
    background: $white;
    color: $black;
    text-align: left;
}
.box {
    @extend %box;

    &-blue {
        @extend %box;
        background: $blue;
        color: $lightblue;
    }

    &-center-align {
        text-align: center;
    }
}

This was you can create styles for the box and only need to change the main class on it to implement it. The rest of the markup inside can remain the same as it is globally defined.

<!-- Blue Box / Third width / Floated left / Rounded Corners -->
<section class="box-blue third left rounded">

<!-- Red Box / Half width / Floated left / Square corners -->
<section class="box-red half left">

<!-- Black Box (uses %box) / Full width of parent / Square corners -->
<section class="box full">

Media Queries

I use a SCSS map and mixin. The SCSS map gets set in my _settings partial and then the mixin will sit in a _mixin partial. This allows me to enable media queries for an element as an @include, allow me to keep my code neat, and change my media queries globally, or enable new ones easily.

See the Pen Media Query Mixin by Tom Clarke (@DesignyourCode) on CodePen.0

Commenting

I probably should comment my SCSS more. For almost every project I scaffold it in the same way. I format my SCSS in the same way. I write my classes in a descriptive – says what is does – sort of way. By doing this I pretty much know what my classes are, even if I come back to the project a long time later. I also know pretty much where those snippets will be, and because of the naming and formatting I can take one look either the SCSS or the HTML and know what the other one is doing or how it should be written.

I know not everyone works the same way, so I should comment my SCSS more. If someone else was to pick it up and work on it, they may get confused, or they may not put things where I would. But even half decent CSS is pretty easy to debug, so I won’t dwell on this too much. When it comes to Javascript…very different matter.

However…

Even when it comes to comments I am still OCD about formatting. In my SCSS I will always add comments on their own line, above the section they are referring too – and including a line break before the comment if it splits the properties…this just adds to readability.

.box {
    // This is extended from %box
    @extend %box;

    &-blue {
        // This is also extended from %box
        @extend %box;

        // This is overriding the background from %box
        background: $blue;
        color: $lightblue;
    }

    &-center-align {
        text-align: center;
    }
}

Often people will add comments to the end of a line that it is related too. There is nothing wrong with this, but in practice I find it can be annoying if the comment is long and goes off the page.

.box {
    // This is a really really long comment that will span off the end and doesn't really explain anything. This extended from %box
    @extend %box;

You can see having to scroll to read it is a bit annoying. So I will make sure that I split the comments into multiple lines — the same way I would in PHP — and each line will get shorter. This encourages me to keep the comments concise. I’ll be honest, I got this idea from Laravel 5. Again this has absolutely no impact on code, but it does help show attention to detail and just makes you think about what you are doing more.

.box {
    /*
     * This is a really long comment
     * I am splitting it across
     * Multiple lines.
     */
    @extend %box;

My HTML follows very similar ideas. Like SCSS, each new comment line within the same block will begin with a capital letter and each line gets shorter. Again this is mainly for looks, and makes you think about what you are writing.

<!--
 // This is a html div tag for a section
 // Any classes here will be assigned
 // After the parent definition
 // Of 'section'
-->
<div class="section">

Overriding

Never use !important. Need I say more?

I never use !important, for anything ever. By using the techniques above, and structuring my SCSS in an OOCSS methodology, I find I never need to use !important.

On the very very rare occasions I have had found myself in a position where using an !important tag would be fast and work I still haven’t. I took a step back, looked at my code and look at my inheritance. Once I had adjusted it, I found that some of my code wasn’t structure as well as it should have been…problem solved…still no !important.

I also never use an ID selector in my SCSS. I am as strict with this as above. If I am having to implement an ID for a specific selector then my code isn’t quite right…back to the drawing board to adjust.

Minor formatting

You’ll have probably noticed from my examples that I use hyphens in classes. I do this for consistency and to reduce confusion. I never use underscores or camel case. I reserve those for use with javascript or PHP. When writing sites using say Twig I tend to use underscores as my consistent format. For AngularJS I will use camel case.

By having these consistent patterns, I find I can identify what is going on quicker, even when I haven’t worked on a project for a while. Angular’s directives can cause issues as they use hyphens as well, but I find I don’t usually apply classes to a directive, but to the template inside so I don’t run into problems.

<!--
 // Angular directive with intro parameter
 // This will never have a class
 // Any classes will be in
 // The template itself
-->
<modal-dialog intro-title="This is the heading"></modal-dialog>

<!--
 // Inside the 'modal-dialog' directive 
 // Is the template that will
 // Contain classes
-->
<div class="modal-window">
    <div class="overlay">

    <div class="intro-title">
        {{introTitle|capitalize}}
    </div>
</div>

<!-- A div with the class applied -->
<div class="intro-title">

You get the idea. I know this has been focused a bit on the HTML side of things, but I wanted to show how my SCSS methodologies overlay with other languages.

@todo

I generally use one way of todo writing, across all languages, and so far it seems to work fine for me. I will simply put @todo - whatever needs to be done as a comment above the section that needs to be looked at.

// @todo - improve class names
.box-container-left-full {
<!-- @todo - swap section class for section tag -->
<div class="section">
{# @todo - issue with date in twig controller #}
{% for post in posts %}
    {% set date = post.date_time.current %}

Plans for the future

  • Currently I am not doing anything in the way of ‘linting’ and want to. I think it will add an extra layer of neatness and control and will help reduce some of the code. As well as time spent debugging. We shall see what happens on the next project. Gulp offers a few solutions for this so it should be quick to implement.
  • I also don’t create source maps, I don’t think it works well in Chrome, so for now I will leave that one alone. I often revisit this, so some time soon maybe.