Sass - acnorrisuk/coding-style-guide GitHub Wiki
Variable Names
Variable names should be chosen for reusability and flexibility. Try to abstract them as much as possible.
// Too specific
$purple: #673667;
$navigation-grey: #777;
$footer-text: 0.8em;
// More abstract
$brand-color: #673667;
$medium-grey: #777;
$small-font: 0.8em;
It can also be useful to adopt a naming convention to make it easier to remember variables across projects.
// Using a standard convention ($type-variation)
$color-brand;
$font-small;
$pad-medium;
$break-large;
Sass's built it colour functions can be useful for making variations of commonly used colours (such as for a button hover state):
// Built in colour functions
.widget-dark {
color: darken($brand-color, 10%);
}
.widget-light {
color: lighten($accent-color, 10%);
}
Nesting
Nesting in Sass should be kept to a minimum to avoid specificity issues and unneeded complexity. As a general rule, if there are more than 3 levels of nesting then the code should be refactored.
// Hard to read and maintain
.top-nav {
ul {
li {
a {
color: green;
&:hover {
color: blue;
}
}
}
}
}
// Better
.top-nav__link {
color: green;
&:hover {
color: blue;
}
}
Sass provides the &
selector to nest items without creating extra specificity. This may be used as the CSS gets flattened on compilation.
// The very useful Sass ampersand
.button {
padding: 1em 2em;
font-size: 1.2em;
&--large {
padding: 2em 3em;
font-size: 1.5em;
}
}
// Compiles to:
.button {
padding: 1em 2em;
font-size: 1.2em;
}
.button--large {
font-size: 1.5em;
padding: 2em 3em;
}
Organisation
To help create more organised code, Sass files should be maintained in a list of partials. This makes it easier to work on code. A typical structure might be:
- Base (for normalize and resets)
- Settings (for variables/mixins/helper classes)
- Components (reusable and shared components)
- Vendors (for plugins / addons)
|-- Base/
| |-- _base.scss
| |-- _normalize.scss
| |-- _custom-resets.scss
| ...
|
|-- Settings/
| |-- _settings.scss
| |-- _variables.scss
| |-- _mixins.scss
| ...
|
|-- Components/
| |-- _components.scss
| |-- _buttons.scss
| |-- _forms.scss
| ...
|
|-- Vendors/
| |-- _vendors.scss
| |-- _colorpicker.scss
| |-- _jquery.ui.core.scss
|
|
-- style.scss
# imports Base, Settings, Components, Vendors
Vendor Prefixes
Vendor prefixes do not need to be written as Autoprefixer can be ran during the compilation step using a task runner.
// Life is too short for this, let the machines do the work.
.button {
-webkit-border-radius: 12px;
-moz-border-radius: 12px;
border-radius: 12px;
}