groups of seeds

Keeping CSS classes together by usage

I’ve written before about keeping your CSS grouped by component, so that styles for a specific part are not distributed wildly around the project and difficult to find.

This is normally done because of media queries. A common thing people might do is to split the stylesheet into 3 chunks. Styles for mobile, styles for tablet, and styles for desktop (or more, depending on how many breakpoints you decide to have). But I prefer to put all styles for a specific component in one place, to save you chasing these around. Even if it does mean having loads of media query declarations. But that doesn’t matter! (I use variables for these anyway).

So ALL styles for a navbar will be together. All styles for a searchbar component will be together.

Another reason you might want to split your stylesheet is to put all print styles elsewhere. With my theory of keeping all styles together, this should mix print styles with screen styles too. This is where I think it gets a bit messy. Sometimes I do, sometimes I don’t. Purely depending on how much is needed to style for print.

Something I struggle with is finding the correct place to write cascading styles from a coloured section. So, say for example I have a light-coloured website with dark text. The h1 is hard, the h2s and h3s are dark. So are the links, and the blockquotes etc.

So what about when I create a section which is dark? All h2s and h3s should be light. All links are light, and blockquotes etc. Do I do this?

p {
   color: $color-dark;
}

h1, h2, h3 {
   color: $color-dark;
}

.btn {
   background:$color-dark;
}

.dark-section {

   p {
      color: $color-light;
   }

   h1, h2, h3 {
      color:$color-light;
   }

   .btn {
      background:$color-dark;
   }
}

Because the problem with the above is that it will soon get out of hand. I pretty much have to duplicate every style inside the dark-section, but give it a lighter colour.

It goes against my idea of keeping all styles for a component together, because styles for some components might end up being much further from the rest because they need to be overridden in these .dark-section styles.

A cool new revelation

I found this out today and it’s amazing. In SCSS you can do this:

p {
   color: $color-dark;

   .dark-section & {
      color: $color-light;
   }
} 

h1, h2, h3 { 
   color: $color-dark; 

   .dark-section & {
      color: $color-light;
   }
}

.btn {
   background:$color-dark;

   .dark-section & {
      background: $color-light;
   }
}

By adding a nested class followed by an ampersand, this turns into the following css:

p {
   color: #000;
}

.dark-section p {
   color: #fff;
} 

h1, h2, h3 { 
   color: #000; 
}

.dark-section h1,
.dark-section h2,
.dark-section h3 {
   color: #fff;
}

.btn {
   background: #000;
}

.dark-section .btn {
   background: #fff;
}

Keeping all related styles together so you don’t have to chase them around.