Creating a sane frontend: CSS file structure

This is a follow on from my thoughts on a robust CSS methodology for big projects, and will be a more actionable post, based on the decisions I’ve made thus far.

How you sort your code is definitely one of the most important considerations when starting any project. And especially with CSS, because the logical divides aren’t as obvious as they might be with HTML or other languages.

Traditionally to reduce http requests, css is pushed into one big monolith of a file. Thankfully between scss and the Rails asset pipeline we’re using on this project, that’s been largely averted. Nevermind the fact that with http2 there is a compelling argument for many smaller files over one big one.

With that in mind, here is what I believe is an efficient breakdown of CSS files and what each one should contain.

Overview

Here’s the basic scss structure, in the assets/stylesheets folder. Please bear in mind that this is built with our current project in mind, and makes a fair amount of allowance for maintaining legacy and new code within one project. If you’re just starting a project from scratch, you should be able to eliminate the /legacy folder as well as /overrides/_defence.scss.

  • /libraries
  • /defaults
  • /components
  • /overrides
  • /legacy
  • application.scss

/libraries

All third-party libraries go here. In our current project that includes Bootstrap, Font Awesome and some Bootstrap plugins.

/defaults

SCSS files only and handles all the site defaults. This would include setting up color and typography defaults, media mixins, helpers, etc.

These fall into the following files:

  • _colors.scss – holds all color variable names. Both general defaults as well as for all themes.
  • _fonts.scss – just holds any external font inclusions. I find it simpler to separate this from the typography mixins & defaults below.
  • _typography.scss – contains all font stacks, font-weight and letter spacing sass maps (more on this in another post).
  • _helpers.scss – all helper/utility mixins & classes – like sticky,  left/right align, etc
  • _media.scss – media query mixin(s). more on this in another post.

/components

This will hold all component styling. Components are currently divided into 2 primary types:

  1. Simple Components
  2. Complex Components

Depending on the number of files, it might be worth having an _index.scss in each root folder that includes all the components there, so that the application.scss file (see below) doesn’t get too cluttered. I don’t see this really being a requirement with any of the other folders really, unless maybe there are a large number of 3rd-party files in /libraries.

Common Components

These would be all general components not specific to a template file and are usually simple components.

Examples would be buttons, icons, logos, lists, general typography, etc.

All common templates should be in the common folder, ie: ../components/common and saved with the component name, eg _button.scss or _headers.scss

Complex (or Template) Components

Complex components would be any component that has a single purpose made up of any number of common and complex components.

Ideally, all complex component styling should be strongly coupled to the template component itself. The best way to achieve this would be to have the CSS in the same folder or even file as the rest of the component code. I, personally prefer the separation of each code type to its own file as much as possible.

With the rails asset management, as far as I know, all CSS needs to be in the stylesheets folder, so to ensure tight coupling, the folder structure for the SCSS file needs to reflect that of the actual component, even though they’re physically in different places in the codebase.

Additionally, our code base is broken into template based views, that may contain one or many complex components, so because of that I’ve selected to name the folder containing all the complex components ‘templates‘ instead of ‘complex‘ but feel free to use the naming convention that you feel best reflects your project structure.

Naming convention: all component-specific CSS should be in its own file and follow the same folder structure as the component it is styling.

So if a component file is in :

../templates/dashboard/widget_franchise_invoices.ejs,

the SCSS file would be:

../components/templates/dashboard/_widget_franchise_invoices.scss.

/overrides

The overrides folder will hold 3 main file types.

  1. Any third-party library changes
  2. _defence.scss
  3. _shame.scss

Library Overrides

There are times that there’s some weird code in a 3rd-party library that needs to be squished or changed. Rather than messing about with the library code (which is never a good idea), rather create a file and override it here.

Follow the following naming convention append ‘-mod’ to the library you’re changing:

E.g. If you wanted to override some styling in bootstrap-toggle you would create a file called: bootstrap-toggle-mod.

In defence of shame.

defence.css and shame.css – both come from some tips I got from this fantastic video/slideshow by Harry Roberts on refactoring css. I highly recommend you have a watch.

https://webexpo.net/prague2016/talk/refactoring-css-without-losing-your-mind/

_defence.scss

This file is specifically used when one needs to override the old site styling (which we inherited) before writing new styling on top of it. The reason for this is so that the new css is clean and remains unaffected by any old code that’s still hanging about. In all honesty, this has had limited use so far, and I find it simpler to, where possible, rather remove the old css. However I’m sure there will be cases where this won’t be possible (because of reliance on old styling in other parts of the app that we haven’t yet addressed), and that’s why I’m keeping it around. The idea is to scrap it as soon as we move entirely away from the old css files.

_shame.scss

Similar to _defence.scss, shame is there for all the quick and dirty and old-browser tricks you might need to do but hate doing and really don’t want to muddle your squeaky clean CSS with – all that crabby (!important, etc) code goes here. It’s named in a way that would hopefully push any self-respecting dev to use it as a last resort – it always should be – but sometimes you need a place to hide the shitty code, and making provision for it means that you can rest easy knowing everything else is sexy af.

/legacy

This is where all the legacy css would go. I don’t really want to talk about it.

application.scss

This bad boy ties all the other things together and is a staple of the Rails asset flow. It basically serves as an index of all of the above files.

As a general rule, here’s how the files are imported:

  • All library files, with the css reset loaded first.
  • all.css – all legacy css would go here.
  • Any library overrides in the /overrides folder
  • overrides/defence – a fat layer of normalising css on top of the old inherited code.
  • All /default files.
  • All /components/common
  • All /components/templates/…
  • overrides/shame – sits on top and overrides everything.

…finally.

Wow, that was a lot more than I expected when starting out with this.. hehe.

Thoughts on robust CSS methodologies for big projects.

There has already been a lot said about ways to handle CSS in growing projects and as frontend development has been my career nomenclature for many years now it is something I’ve mulled over and had to practically implement more than just a few times already.

I think the best solution I’ve found, is react-css-modules. Unfortunately, it is rather deeply tied into the tech stack that it is built on.

Why I like ReactCSSModules

  1. All CSS is strongly coupled to the components it describes.
  2. Presuming 100% adherance to the methodology, there is no chance of unwanted styles creeping in.
  3. Because each file only contains the css for the component it is describing, it’s very easy to find where to make changes (or fix bugs)
  4. The possible downsides like code repetition can be averted with a few good tooling options (ala PostCSS) and gzipping the output.
  5. Closely follows the standard CSS/HTML implementation (implementation into the HTML code was as simple as using ‘styleName’ instead of ‘class’).
  6. Ease of use – there is very limited ‘brain-drain’ or cognitive load with no need for naming conventions (I’ve found naming components takes up a considerable amount of mental effort as well as time when building out any new components) or having to worry that my carefully named component conflicts with some other component built 6 months before.

This was the case with the previous project we worked on at Ekaya, where we were able to build everything mostly from the ground up, using a Node & React stack and (once we got it all setup and running) it was glorious.

when you can’t use the perfect stack…

However, our latest project is an inherited Rails behemoth which we’re now both refreshing the styling and building in new functionality and moving away from the standard Bootstrap-based component structure, which means that we will need to start relying on our own naming conventions & ‘framework’ going forward.

I had a look at the non-react version of cssModules, but it messes with the way CSS is added to the DOM a little too much for my liking, which has pushed me back to having to attempt to build out as much of the happy-sauce found in cssModules, but manually and ideally in a way that makes it easy for new devs to quickly get up and running.

What I need in a solution

As I consider a solution, I’m looking to ensure:

  • a solid naming convention – I’m leaning towards something BEM-inspired
  • the separation of CSS into SCSS files by component to reflect the code base as closely as possible
  • sane defaults to reduce cognitive load and ensure consistent styling across the app.
  • A balance between class names as style descriptors and class names as component definitions (think class=”button button-blue button-outline button-large button-no-drop-shadow” (Bootsrap-esque) vs class=”widget–stats–button-outline” (more BEM-like) )

And there are a bunch of things that will need some deeper consideration, like

  • the nature of the project means we need to handle theming,
  • Would need to work with the inherited Bootstrap framework where possible (Grid system, etc) and
  • Finding a way not to have it all devolve into css-soup in a month or two (or as soon as there’s more than just me working on the codebase).

That’s it (for now)

That’s as far as I’ve gotten in my thinking on it (well in a way that is communicatable), but this is definitely an ongoing journey, which I’ll keep posting on until I have some sort of usable solution…

Feel free to weigh in if you have any thoughts <3

Journaling and Stoicism

I’ve been getting into stoicism for a few years now, and have really enjoyed anything and everything coming from Ryan Holiday. He recently launched Daily Stoic and an accompanying newsletter.

One of the first entries talk about morning and evening rituals and the importance of journaling and taking stock of your day, so yesterday I went and got me a red hardcover Moleskine and for the first time in years, wrote a journal entry.

I figured as a partner to that, I’ll post any snippets and thoughts I wanted to highlight or share here, so expect to see more of that over the next few months.

 

x

Cam

Cool Links from the Week

Inline front-end simple wysiwyg editor.

SDK for vector maps for mobile

Quickly detect hacks with CRON & PHP

Sketch Tools: Save Colour Palettes

A collection of podcasts for startups

One button to rule them all. Open Netflix, dim the lights, silence the phone and order food. Boom.

Some amazing Chrome DevTools

View story at Medium.com

Collection of stylesheets and snippets

 

Keeping on keeping on.

Perseverance. Discipline. Self-control,call it what you like, but the ability to stick with something throughout all the ups and downs, through the passionate jungle lands and long treks through the dry deserts of pure hard work, is a special skill.

Gary Vaynerchuk calls it his hustle.
Nike uses the slogan “Just Do It”.

Whatever you want to call it, it’s all about keeping your head down, shoulder to the grind stone and nose in the dirt.

It’s about Action.
About Grit.

But remaining focussed and committed and to maintain the belief that your plans will succeed is one of the primary factors for success. It’s also one of the things I seem to struggle with the most.

I feel like I have a ton of potential (I love and hate this word), I have dreams and things I see myself being able to achieve. And I get that it’s hard for everyone – if it was easy we wouldn’t be drawn to the GaryVees of the world, because we’d all be getting it right anyway.

It’s frustrating though. This is more a rant than a 5 steps to making your hustle work. Honestly, I’m not sure how to. I have all the theoretical knowledge – at the very least, enough to get started – but somehow somewhere I just can’t or don’t. My head goes blank whenever I have free time, but when I’m busy, then it’s filled with all the cool things I could or should be doing.

I’ve got Trello boards filled with ideas. And cool shit I want to do. Overload and too many ideas is probably a real issue here. Busy-ness too. Distraction for the sake of distraction.

And Fear.

Fear of losing. Fearing of success. A whole lot of fear. There’s a thousand reasons why not. I’m doing my best to push through it – but the noises are loud. The excuses many. And the distractions innumerous.

Our minds are weird things. What I long for the most, I seem to do everything to avoid achieving. Every little issue that I could formulate to stop myself getting somewhere I will. It’s annoyingly frustrating.

I’m determined to get there, but it’s really hard to see the wood for the trees sometimes.

I think through all the struggling and reading and listening to podcasts, talking to friends, thinking and watching others succeed and how they did it, I’m starting to formulate some kind of a way forward. Some way to hack my way to the surface.

I know I said this isn’t a 5 steps post, but maybe it is..

I think the keys points are :

1. Work hard and smart. Cliche I know. But for me, I’m always “working” but really I’m usually not. I’m distracting myself with something. Often times it’s aimlessly scrolling through facebook. Or going through newsletters and clicking interesting posts that I’ll probably never read because I open too many and then save them all to Pocket or Evernote in the hopes that one day I’ll go through them but never do.

So I need to start working. Actually working. On something. Anything. Even if it’s scary.

This means planning or giving myself a task. That’s important – preparing my mind for work. Just sitting down and then going ok I need to work here’s the work let’s go never really works. At best I end up writing about it (queue this post) at worst I end up lost in my Facebook news feed hitting refresh in the hopes I’ll be entertained.

2. Treat everything as an experiment. That way if you fail, it’s not really failing – it’s simply data that can be taken and used to rinse repeat. Success is the same – data. Rinse repeat- see what I’ve done right or wrong and how I can make it better.

What I can use to make it work for me. Because otherwise, honestly both ‘success’ and ‘failure’ can be a trap that leads to stagnation, which is failure. As with most things in life, annoyingly, we’re always moving. Either it’s positive or it’s negative but it’s almost never still.

3. Break the work into smaller pieces. The big tasks always overwhelm. I end up staring at it for 10minutes then checking Facebook and remembering 30min later that I was actually doing something. Especially if it’s something new or hard or that I’m not 100% comfortable with.

Breaking things into bite-sizable bits helps me be able to figure out in my head exactly what I need to do then get on and do it. It creates small actionable bits for each piece of the work. Solve one piece then move on to the next. Rinse repeat and soon the project is done. Elephants and single bites and all that.

Sometimes what happens is that I don’t break things down small enough, and so I end starting something and then not getting anywhere – so what helps is whenever you start a task, see if it can be broken down further – and rinse-repeat this until you can knock off each task easily and gather a nice momentum through the work.

4. Plan everything. This ties heavily into #3. The only way you’ll be able to break a project down into actionable bits is by taking a few minutes out to plan. I’m always the most productive when I plan first. Planning gives me a good overview of what I need to achieve overall, it makes sure that I haven’t missed anything and then it allows me to break the project into smaller tasks and catch anything that I might need to consider or plan for down the road.

5. Focus. Focus is insanely important to achieving anything. It’s the ability to keep on at a task or project without being distracted by all the miriad distractions that abound – especially when your work depends on being so heavily connected. Always online, always available. This is where a good plan goes a long way. Knowing what you want to achieve and how you’re going to go about doing it is a fantastic way to encourage focus and discourage procrastination.

6. Get Started. Just Do It. The Art of The Start. Hustle. All the gurus are saying it. It’s the hardest part – just get going. Just start. Just do the fucking thing. Why is it so scary? All the reasons above – fear of failing, fear of succeeding, fear of well pick something and it’ll jump in and distract. Simply get started.

I’ve found the best way to start is to define what you want to achieve. Set your goal. Any goal. If you don’t know where you want to end up – then at least decide where you want to be in a month. Define what you want to achieve – it’ll probably change anyway – but get it down. Then using planning, break it down into smaller chunks, and as I’ve said above-  it makes it less scary, gives you something to focus on now. Something achievable. And something that ties into a bigger picture. It’s your roadmap. You’re paving the road as you go, but in the back of your head you know where you’re going.

These are some of the tools I’ve used -and I’ve found really helps with getting me onto a project and productive quickly. There’s almost definitely a few more.

I know them and yet they’re still so difficult to use. Usually it’s because I think of something rad, get scared then forget the process and don’t get anywhere – so having it here written down will hopefully serve as a much needed reminder.

And hopefully it’ll help you to get going on whatever dreams and goals and side projects you have in your heart to do.

Focus and the Beast.

There is a lot to be said for focus. The ability to focus on a singular goal can help one achieve some amazing things.

I’ve been growing a theory that indecision is the leading factor that keeps me from achieving my dreams. That and laziness. Actually not laziness, but fear. And maybe a bit of lazy. Although it’s not lazy.. it’s lack of belief that I can achieve what I set out to.. But they’re all tied together I think.

Indecision leads to inaction. Which leads to, well, nothing. It leads to maintaining the status quo. The easy way out is also the quickest way to land yourself in a dead-end.

One of my favourite authors and life hackers, Tim Ferriss has stated that he believes it is possible to become world-class at something within 6 months – so twice a year. Simply through focus and finding the quick gains.

And it’s these 3 things that tend to leave me in mediocrity.
Indecision. Inaction. Fear.

I always feel like I suck at getting things done. I struggle with focus. My focus seems shit at the best of times, but I’m beginning to learn how to hack periods of concentration back into my life.

The thing is I don’t lack at all in having ideas or goals. Vision maybe a little- but again that’s more because of a lack of believing I can achieve what I set out to. Lack of self-confidence really.

As a result of knowing there’s an issue, I’ve spent a ton of time thinking about how to fix it. I’ve also tried to look at what’s worked for me in the past. And I’ve found that it’s a lot easier to focus when I have a clear picture in my head of where I’m going, what I need to do to get there and the task I need to do right now.

Unfortunately more often than not – it’s deciding those 3 things that proves incredibly difficult, but when I spend the time figuring it out, it really helps pull whatever I’m working on from an idea and closer to reality and having that purpose and a defined idea of what to do now and what comes next really creates a space for focus. That and tackling one thing at a time, which is a whole other kettle of fish…

 

I’m so meta right now.

tl;dr I need to write, therefore I’m writing. About writing.

I need to write. Which is the primary reason I’m writing now, today. Writing about writing. How very meta of me.

I set out in August to create a piece of content every day. This post will mark my 7th written piece. I’ve created some Snapchat content almost every day, and a Twitter video. I’ve made a weird Beme video – honestly, I don’t know that I like it. It feels… weird.

But, I think I’ve missed a day or two, which kinda sucks.

So far I think it’s the fear more than anything.. I have this weird fear of writing. To write, I need a topic (Or like tonight, I don’t), and there’s this strange fear. No, not fear. Anxiety. This this strange anxiety around finding or at least accepting a topic. I suppose it’s almost that once I accept a topic to write about – I then need to embrace it. I don’t want to fuck it up or sound silly or come across ignorant. I’m still at that place where I fear societal backlash if I say something stupid – which is in itself stupid because the number of people reading what I write is so small and 99% are friends who tend to be very nice and encouraging about it all (thanks guys).

But.. in the back of my head I know I need to write something. Anything. And the irony is that as soon as I sit down to write the words come. I’m pretty opinionated and know a bit about a bunch of stuff, so I never really struggle to write about something once I’ve chosen the topic. But still, anxiety.

And it’s that anxiety, and kinda possibly just not feeling like it that leaves me writing my posts usually around midnight, starting just before so that the created date still comes in on the day. But, that’s also meant that a few times I’m simply too tired to write anything, and end up writing something like this..

What happens when I fall asleep writing
This is what happens when I fall asleep writing…

But that’s the moany part. I figure it needed addressing. I really want to finish the month strong. I have a bunch of stuff I’d like to write about – but I also know a few of them will take time which I need to make time for, but everything pays a price.

Writing this means that either I’m going to go to bed later or I need to fill in my expense slips another day. And they’re kinda piling up.

But this writing thing is good. I’m starting to be aware of what I want to write each day. I’ve been thinking about things more and it’s pushing me to read again (which is only ever a good thing).

I really want to do some vlogs. I’m looking forward to messing about with some video editing, but also just getting some videos out. That scares me on a different level, though. Mostly because it’s me. On a screen. Talking and shit. What will you people think!? And more importantly – what will I say?

On the vlogging, I think I’m really just not sure what to do. I mean I could do a bit of a standard vlog journal thing, or do more of a technical tutorial vibe. Arguably I should do both. The experience will do me good. I don’t know – you guys have any tips or advice? Pushing little videos to my Snapchat daily journal thing has been fun – but one can’t say much in 10s, and it disappears so quickly – I’d like something with a little more permeance – even if it’s simply so that I can go back and look through things, and build up a bit of an archive. I think that’ll be a rad thing to have.

While we’re on Snapchat – I really really like the text-overs and how they handle Emoji. It looks like they’re going to start bringing in image overlays too (if GaryVee’s vids are anything to go by) which will be very cool. Why is no one else doing this? I wish I could record a video or take a pic on Whatsapp or Instagram and easily be able to overlay text or scribble some silliness on it. Would be rad.

Ok well that’s it – and my first official ‘journal’ entry.

Chat again soon my lovelies.

x

The price of choice

Choices are expensive.

And not just because of opportunity cost, but because of the impact that making a choice has on us.

That’s why discipline is so hard. Or any kind of change where we aren’t being driven by passion or some form of natural motivation.

We are creatures of habit. And once we’re headed in a direction it’s very hard to change it.

That’s why trying to make changes outside of our norms is so taxing on the mind. I’ve always found it hard to illicit change in myself. Even when it’s something I really really want to see happen, the energy only lasts so long before it runs out.

As an illustration, I’ve been focussed on weight loss and fitness for the last four years. It’s been an up and down road. 

Over the years, a few things have settled as habits, but I’ve also found it harder and harder to remain focused on eating right. 

And honestly, I’ve always found that focusing on exercising was a lot easier than focusing on eating, and I think I know why. 

Exercising is an active thing. Once I do it I always feel better, it feels like I’m proactively changing, and so I think it’s a lot easier to keep motivated with it. Eating, on the other hand, is very passive. There are some immediate impacts of eating healthily over not (less chance of feeling bloated, etc) but generally it doesn’t feel very active. 

Additionally, I think the main issues boil down the to the number of decisions one needs to make for each.

When exercising it’s really a matter of deciding when to exercise and what to do. And typically it’s three to four times a week. 

Eating on the other hand is deciding what to have, and that includes remembering what you can and can’t eat as well as usually having to make (or pre-make) food, three times a day, six to seven days a week (if you’ve got a cheat day). And it’s not just three times a day, but it’s also repeatedly choosing not to indulge that chocolate or pasta craving, and that typically happens a lot more than just at eating times.

So, in summary, where exercising requires you to make the right choice maybe 8 times in a week, with eating it’s upwards of 50. And all those choices tire out the brain and willpower. 

The other side of it is that the more you make the right choice, the easier it is the next time, and so, arguably, making 50 right choices in a week means it should set in as a habit a fair amount quicker than the 8-odd times with exercising. 

Thankfully, though, there are tools one can use that reduces the day-to-day choices and makes it a lot easier to instigate change consistently.

A bit more on that next time.