The document provides 10 rules for writing awesome CSS:
1. Do not nest selectors unless absolutely necessary to avoid specificity issues and difficult to maintain code.
2. Use the least specific selector possible by selecting elements over classes over ids to make styles easy to override and change.
3. Avoid using !important as it is not a permanent solution and will create problems later. It is better to fix specificity issues with CSS structure.
4. Standardize formatting like using multi-line code and indentation to improve readability and version control of CSS files.
5. Make CSS modular by separating into base, module and layout rules to organize the code like Lego blocks.
6. Split modules into
11. LEAST SPECIFIC SELECTOR
∎ Easy to override
∎ Easy to change in the future
∎ Gives markup structure, hierarchy of elements is clear
.nav__link {
color: blue;
}
23. ∎ Only for use when you know that you will never want to
override the value in the future (how often does that happen?!)
∎ It is not a quick fix solution, take a step back and look at your
CSS structure, is it too specific?
∎ Will create bigger problems for you in the future.
!important
26. EASIER TO READ?
OR
.nav__list {
width: 600px;
margin: 10px 20px;
padding: 10px;
background-color: #669900;
}
.nav__list ul li a { width: 600px; margin: 10px 20px; padding: 10
27. ∎ Use multi line! It will help with version control and general legibility
∎ Indent your attributes
∎ Choose a type of indentation and stick with it
∎ Use a CSS linter
This will help keep your attributes in a sensible order, will keep
units and shorthand in track and will flag parsing errors
FORMATTING
31. BASE RULES
∎ Applied with an element selector
∎ No classes or IDs
∎ Define default styles
∎ Includes
□ Reset styles
□ Typography
□ Colour and size variables
32. MODULE STYLES
∎ Break your design up into discrete sections
∎ A module can be a single element, a group of elements or a
group of groups, you decide what works for your design
∎ Eg. Navigation bar,
carousel,
dialog box,
article,
spaceship...
33. LAYOUT RULES
∎ Layout rules define where
your modules go
∎ They are the ‘major
components’ of the page
∎ Eg. Header, footer, sidebar.
39. NAMING YOUR STYLES
∎ Check out the BEM naming convention
∎ Choose a convention and stick to it
∎ Makes your styles easier to debug and search
∎ Simpler for multiple people to work on
43. GO FORTH &
Any questions?
You can find me at @thisisjofrank
do feel free to ask me questions on there too!
CSS WELL
44. RESOURCES
Jo’s talk on BEM and SMACSS (with speaker notes) -
https://docs.google.com/presentation/d/1Vb3_OkFVh3j-qkH6ZoZIEy2XDY7I23LPfAMkiMRDqJA
A great article on specificity
https://www.smashingmagazine.com/2007/07/css-specificity-things-you-should-know/
CSS Help
https://css-tricks.com
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started
Editor's Notes
At codebar we’re always trying to learn new things, and this is great, however it is also important to learn how to improve the way we do things we already know.
CSS can be deceptive, it is quick to pick up and get moving with, you get cool looking things on the page instantly, hi
but sometimes our CSS can run away with us, especially if we’re using something like bootstrap,
or working on a legacy project.
It can be messy to read and difficult to maintain, which are things that no one wants in their code,
So I’m going to give you 10 rules to help you write good, readable, maintainable CSS
So let's get started, as programmers we know that counting starts at zero, so rule zero
*
Rule zero is Do Not Be on Fire,
an important rule that you should aim to adhere to in all walks of life,
When you're on fire you're unlikely to be writing your best CSS.
So, rule one. The least specific selector is the best.
Lets illustrate this with an example, take a look at this HTML
We’ve got a navigation which contains a ul, and an li and an a tag
If i asked you to apply a style to the a tag, how many of you would do something like this?
If i asked you to add a style to the link,
how many of you would select the link like this? Be honest!
What we’ve got there is a very specific selector
*
See what you’ve done to emmet?!
But what do I mean when I talk about specificity?
Specificity determines, which CSS rule is applied by your browser.
and it is usually the reason why your CSS-rules don’t apply to some elements, even if you think they should.
If we had two selectors applying to the same element, the one with the higher specificity wins
*
There are four distinct categories which define the specificity level of a given selector,
in specificity order these are inline styles, IDs, classes+attributes and elements.
So, if we take a look at our selector from earlier
we’ve been pretty specific here, there is a class and three elements,
Imagine if you joined a team and were working on someone else’s giant css,
the site is huge and you’ve been told to change the link colour from green to blue
so, being the awesome front end developer that you are, you know to use the least specific selector, so you put your style in with a single class
*
but alas, the arsehole who wrote the original css has screwed you over, your link is staying green.
/this/ is the problem with being unnecessarily specific.
So, when you’re writing your css, make everyone’s lives simpler by using the least specific selector possible!
How did we know that that was the least specific selector?
well we could apply the style to the element, in this case the a tag
But if we do that we’re not going to be able to apply many styles,
we might not want every a tag on the page to look the same,
so what is our next option?
The classes
A good rule of thumb is that if you wanna style it, then you shoulda put a class on it,
then you can use that class in your css! Nice.
As a side note, look at how high up in specificity the ids are, want to avoid future issues? Don’t apply styles using IDs!
Easy to override
Easy to change or remove in the future, you can tell immediately what the styles are applying to
Gives markup structure, hierarchy of elements is clear
Emmet approved
So now we’ve got our specificity down, rule two is
No nesting or combining classes!
*
Unless for some reason you really can’t avoid it.
*
I’ve seen CSS that looked like this before
*
SASS is really great, it has a load of tricks to make writing your css easier,
one of those tricks is that it lets you nest your selectors inside each other to create really specific selectors
But wait, didn’t we just say that specific selectors are bad?
Yeah we did. Don’t do this
*
even emmet knows that.
Unnecessary levels of specificity
Difficult to override
Difficult to maintain and read, we’ve ruined the clear heirachy of our using just class selectors
Nightmareish code created by Preprocessor
so, somehow we’ve ended up with this html
we’ve got a lot of classes on there, but not everything has a class
They’ve not been following beyonce and putting a class on it
not only that but
and for some reason there are lots of nested divs, maybe because we’re using a CMS of some kind which has caused them to need to put lots of elements on the page
Now, this is a think that i’ve actually seen in CSS
The developer thought they were being really clever
They’ve mirrored the css structure to match the nesting of the HTML
*flick back between slides*
They thought this was great because, who knows,
it is an interesting idea, but crazy, what a waste of space, they might not have even needed most of those selectors
what really shows that this is mad is if we look at the compiled css
holy combined classes batman!
So, nesting, or, if you’re not using SASS, then combined classes
If you must, for example if you’re using a CMS and you can’t add a class, then try to keep it to an absolute maximum of 3 levels
Allowable exceptions are pseudo classes, so :hover, :before, etc, you need to nest/combine in order to actually use these
So, that same arsehole that ruined your styles from before is back,
you know how to sort this, use !important to override their styles!
No! Bad!
Only use !important when you know that you will never want to override the value in the future (how often does that happen?!)
Don’t use !important as a quick fix to an immediate problem.
Usually the real fix will be to step back, look at the structure of your CSS and refactor it to make your selectors less specific.
If you’re abiding by rule 1, you should never need !important
Using !important lazily will create bigger problems down the line as your site grows and you need your CSS to be as flexible and non-specific as possible.
Standardising your formatting will make it much easier to work together with others on a project, you’ll want to set a standard and make sure that
everyone is sticking with it.
Oooh standard lego shapes.
Lego have standards for all of their blocks, imagine if different lego factories created different sized bricks, or different shaped holes, it’d be a nightmare
and wouldn’t be half as easy to build with
I’m going to suggest some formatting that i think you should go with
Take a look at this example
Which of these is easier to read at a glance?
Use multi line! It will help with version control, you’ll be able to see line by line what has changed, rather than *something* on the one line has changed
and it makes your code generally more legible
*
Indent your attributes, makes reading the code easier to read at a glance, you can see where a selector begins and ends easily.
Choose a type of indentation and stick with it, be it tabs, two spaces, four spaces (ahem which is the correct choice ahem),
swapping indentation will cause you issues with your version control too, it will see that you’ve changed tabs to spaces could flag unnessary change problems
*
Use a CSS linter
Basically, a linter looks at our code and checks for bad programming practices.
Undefined variables, anything you’ve written inefficiently, things like that.
This will help keep your attributes in a sensible order, will keep units and shorthand in check and will flag parsing errors
They can work on the command line, so you can install one into your build process
You can install a linting package if you’re using any front end tooling such as gulp or grunt
You can install one into your editor
you can even use online ones that you have to paste your css into if you’re not comfortable with the above
They make your programming life much easier, lets face it, not many of us possess perfect knowledge of CSS, and even if our knowledge is good, we all make mistakes!
Linters are there to keep your CSS on the straight and narrow.
Make your css modular,
I’ve actually already written a talk about modular and scalable css, which i can link to at the end of this,
but i’ll go over it very briefly here
we can break it down into small components and then use those to build complex pieces
I usually break my modules up into
base rules
module rules and
layout styles
I’ll go over what each of these mean
A Base rule is applied to an element using an element selector itself, along with any pseudo-classes.
It doesn’t include any class or ID selectors.
It will define the default styling for how that element should look in all occurrences on the page.
This, mostly likely includes your Reset CSS, which overwrites the default browser styles
and could also include your typography rules,
your default link styles, ul styles, li styles etc
If you’re using SASS then this would also include your colour palette and sizing variables
Never ever use important when writing your reset styles, i would hope that would be self explanatory.
Discrete components
if we were talking lego, these would be blocks, and groups of blocks put together,
A module can be a single element, a group of elements or a group of groups
We call them the ‘minor elements’ of the page
Modules can be contained within other modules
They can be easily moved about the layout
Navigation bar
Carousel
Dialog
Article
spaceship?!
Whereas modules are minor components, the layout rules refer to major components, so header, footer, sidebar, main etc
your layout rules define where your modules are allowed to sit and how they move about when the page flexes
As your CSS files get larger, they get more and more difficult to maintain
You’ve already split your styles up into modules, so it is a simple task to give each of those modules separate files
Here is my suggestion for file separations -
have a reset file, this is where you redefine all the basic tags for your site. You’ll handle the body, links, headers and such here.
*
if you’re using SASS, make a file of all of your colour variables
*
Have a file with your layout rules, this is like the shell of the site, the outer layer of the site that exists on every page.
The shell will have the site container, the position of the header and the footer.
Frequently, an important job of the shell is to set the width of the website.
*
Make a file for your typography, this will be defined by your style guide, you can lay out all of your heading types, font sizes and icons in here and extend from them if using SASS
*
Next make a separate file for your sizing variables, these will be things like a common ‘spacer’ variable, ours is 10px, if we want variations on that then we multiply it
You could also have your viewport sizes in here
*
Next we’ve got your media queries, these are going to use those viewport sizes to create your responsive rules
*
make a file for any helper classes, such as a clearfix, a ‘text reader’ class to shove text off the page, anything you might need.
*
If you’ve got common styles in your styleguide then make them extendable, for example button styles or container styles, give them separate files
*
and finally, once we’ve got our toolbox of files created, we can actually style each of the components of the page, so these will be the modules that you broke the page up into, give them each their own file
if your files get too long, consider splitting the modules up into smaller blocks, the plan here is to make them easy to maintain.
Choose a naming convention and stick to it.
A naming convention is, essentially how you name your classes, and there are lots of schools of thought on this
At the very basic level it is controlling whether you use lowercase, camelcase, hypens or underscores
at a more complex level it is how you choose the words of the names.
you want your css to be as clear as possible, which is why we went with the single class selectors in rule 1
but if you name the classes harry, ron and hermione, you’re not going to have a clue, looking at your css what it is that you’re actually applying the styles to.
Personally, I am a big fan of the BEM naming convention, which uses the modules that you’ve already created to name your css classes
So, if we go back to the bit of html that we had in the first example
we name the navigation for what it is, a navigation
then the list is inside that, so it gets called nav__list, this helps us, when we’re looking at our CSS to know that it's a list inside the nav
Then the item inside the list
and then we could call the link nav__list__item__link, but that is getting a bit ridiculous, so i chose to name it nav__link
If your class names start getting a bit unmanageable then do the sensible thing and make them manageable, i can still tell that the link is related to the nav
This naming convention doesn’t mention any styles, there is no ‘red box’ or ‘small text’ which makes it much easier to restyle in the future
and you can remove entire chunks of css if necessary and know exactly what they’re applying to
I’ve linked to the talk that i gave on BEM on the resources slide at the end of this talk
You dont have to go with BEM, but do choose a convention and stick with it
you want to keep the identity of your code consistent across a project.
Your styles will be easier to search, easier to read and easier to work out where you’ve made a mistake
They’ll also be much less liklihood that if you’ve got multiple people working on styles that you’ll end up accidentally naming things the same, whereas a name like redBox could be multiple things
No magic numbers!
(sorry unikitty)
take another look at your modules and see if maybe you need a new one
if you’ve got too many variables, that should be a warning that your code is going to be nightmare to maintain/change
think about how many of the styles you need, can you lift individual ones?
download and host yourself, don’t rely on cdn
you’re likely to end up battling styles you don’t want
lots of bloat
Bootstrap is great if you’re making a quick mockup, but really isn’t what you want for a site you’re writing from scratch
You’re much better off writing your own sensible styles!