My Front End Coding Principles


CSS Specificity

One of the important things to understand about how browsers read your CSS selectors, is that they read them from right to left. That means that in the selector

ul > li a[title="home"]

the first thing thing interpreted is a[title="home"]. This first part is also referred to as the "key selector" in that ultimately, it is the element being selected. This means that the selector ul li a will look for all the a's on the page first, then all the a's with a li parent etc etc. This takes time. You won't notice it on small websites, but if anything has any dynamic content being injected into the DOM it will make a difference. Now we will discuss how to combat this.


We will try and namespace our css. This means not using selectors such as:

header {width:100%;}  
header .logo {float:left;} 
header .logo .img {border: 1px solid #000;} 
The above code means that if we wanted to use the class .logo somewhere else, it would not inherit the header .logo{} style above. This also increases the specificity of the selectors, decreasing performance.

Namespacing the above css would look like this:

.global-header-logo-img{border: 1px solid #000;}

This is extremely efficient because of the specificity of the selectors. As you can see the length of the selectors can get quite long, but that is where common sense comes into play. There shouldn't be a need for .header-left-menu-item-link-with-children. In summary, give everything a class and never ever ever ever do something like this .foo div

JS Selectors

If we select an element using javascript to manipulate it we should add a new class. It should be prefixed with js- This ensures no styling conflicts happen. The class should describe the action that the javascript does on the element. For example: .js-open-close-menu This means that you know if an element has some javascript maniplulation asscociated with it. So you don't remove the class and find you make breaking changes.

Top Tips

Never use 0px when 0 is sufficient. Always use shorthand properties where appropriate, padding: 15px 0; not padding: 15px 0 15px 0; When using vendor prefixed features, put the standard declaration last. For example… -webkit-transition: all 100ms; transition: all 100ms; Browsers will optimize the standard declaration, but continue to keep the old one around for compatibility. Putting the standard declaration after the vendor one means it will get used and you get the most optimized version. Comments rarely hurt. If you find an answer online (read: on Stack Overflow) then add the link to a comment so future people know what’s up.

Tags: css