CSS - acnorrisuk/coding-style-guide GitHub Wiki

Style

When writing CSS declarations try to maintain a clear style. Putting properties and values on their own lines aids readability.

/* Clear and easy to read */
.class {
  property: value;
}

You don't need to add units for '0' values. This keeps things readable and prevents mixing units.

/* Unitless values */
.nav-item {
  padding: 0 0 40px 20px;
}

Try to be specific with property names. This helps prevent accidentally overriding previous values which may be used elsewhere.

/* Can cause problems */
margin: 10px 0 0 0;
background: green;

/* Much safer */
margin-top: 10px;
background-color: green;

Selectors

Try to use classes instead of element selectors or IDs. This leads to more predictable and easier to maintain code.

/* Avoid (unless applicable to all headers) */
header ul {}

/* Better */
.primary-nav ul {}

Also, avoid unnecessary specificity where possible. This can often be difficult to override later on.

/* Unnecessary specificity */
div.info-block {}

/* Better */
.info-block {}

If you do need to descendent selectors, it isn't necessary to state every element. Shorter selectors help prevent unneeded specificity.

/* Unneeded specificity */
.main-nav ul li a {}

/* Better */
.main-nav a {}

Comments

Short comments should be added when code is confusing or contains hacks / workarounds which developers need to be made aware of.

li {
/* Makes content line up vertically */
  display: inline-block;
  vertical-align: top;
}

Comment blocks can also be used to delineate large sections of code to aid visibility.

/*
* MAIN NAVIGATION
*
* Provides styling for .primary-menu
*/

Naming

Selectors in CSS should be written in 'kebab-case'. This helps separate it from JS (which uses 'camelCase'). It is also the pattern CSS uses itself when delimiting words (e.g border-radius).

/* Not the usual convention */
.someClass {}
.some_class {}

/* Follows usual convention */
.some-class {}

In many projects it is preferable to use a CSS naming convention. This can help create clear and maintainable code.

/* The popular BEM naming convention */

/* Block */
.subscription-form {}

/* Element */
.subscription-form__button

/* Modifier */
.subscription-form--reversed

It can also be useful to indicate state by the using the 'is-' prefix.

.is-active {}

When using classes or IDs as JS hooks, they can be prefixed by 'js-'. This helps separate the behaviour from the styling and prevents problems as class names may be changed in the future.

.js-modal {}