CSS Standards And Best Practices

CSS Standards And Best Practices

Practices to improve our CSS writing standards

Hello Front End developers,

When writing CSS for applications, often we might end up with confusions in following the standards for writing the style sheets. It may be the naming convention, structure, ordering, commenting etc. Hence this article will discuss on the common practices that can be followed while writing style sheets. These practices will make the style sheets more readable, maintainable and easy to enhance for future requirements.

Without further briefing lets move on to list down the common areas in style sheets where we can follow the standards and best practices.

Selectors

Selector are the key component in writing styles. More responsible and specific selectors are required to target an element.

Generic selectors will be easy to write but its adverse effects will increase the consequences of affecting elements we are not intend to target. Hence proper testing will be needed.

Location specific selectors will target block of elements and can save us time in testing. But it might lead to confused and clumsy style sheet.

Hence use your best judgement to create selectors that find the right balance between contributing to the overall style and layout of the document under construction, that comes with experience.

  • Selectors should prescribe the intended element's purpose.
  • Use simple selectors names that describe what element(s) they style & their state.
  • Avoid camel case when naming selectors. Use only lowercase and using hyphens to separate multiple words. Avoid using special characters other than hyphens.
  • Avoid using over-qualified selectors, div.container can simply be stated as .container
  • Attribute selectors should use double quotes around values.
  • Avoid using shorthand writing for selectors.
  • Avoid using lexical names for the selectors like myDiv, commonDiv, subDiv, spanDiv, etc.
  • Advanced methodologies like BEM are available for naming and grouping the selectors. Use them when possible.

Correct:

#comment-form {
    top: 0;
}

input[type="email"] {
    line-height: 1.1;
}

Incorrect:

#loginForm { /* camel case */
    left: 0;
}

#login_form { /* incorrect name separator */
    left: 0;
}

div#login_form { /* over qualified selector */
    margin: 0;
}

#d1-chcon { /* selector is not understandable */
    margin: 0;
}

input[type=text] { /* incorrect way of specifying attributes */
    line-height: 110% 
}

Properties

Properties form the core of the styles design, hence when defining the properties make sure not to give any fixed dimensions that would hinder flexibility and responsive design issues.

  • Properties and Values pair should have a colon and space as separator.
  • All properties and values should be lowercase, except for font names and vendor-specific properties.
  • Use hex code for colors, or rgba() if opacity is needed. Avoid RGB format and uppercase, and shorten values when possible: #fff instead of #FFFFFF.
  • Use shorthand (except when overriding styles) for background, border, font, list-style, margin, and padding values as much as possible. Shorthand e.g. .box {margin: 10px 20px 10px 20px; } Instead of .box {margin-top: 10px; margin-right: 20px; margin-bottom: 10px; margin-left: 20px; }

Correct:

#selector-1 {
    background: #fff;
    display: block;
    margin: 0;
    margin-left: 20px;
}

Incorrect:

#selector-1 {
    background:#FFFFFF;
    display: BLOCK;
    margin-left: 20PX;
    margin: 0;
}

Property Ordering

  • Order properties by its type, with or without certain exceptions.
  • Top/Right/Bottom/Left (TRBL/trouble) should be the order for any relevant properties (e.g. margin), much as the order goes in values.
  • Corner specifiers (e.g. border-radius--) should be top-left, top-right, bottom-right, bottom-left. This is derived from how shorthand values would be ordered.
  • The order of the properties can be as mentioned in the file here .

Example:

#overlay {
    position: absolute;
    z-index: 1;
    padding: 10px;
    color: #777;
    background: #fff;
}

Vendor Prefixes

The browser prefixes are being used to make sure that the browser supports the specific features/style we want to use. For specific CSS properties each browsers will have its own behavior, hence remember to add browser prefixes as and when required. Vendor prefixes should go longest (-webkit-) to shortest (unprefixed). All other spacing remains as per the rest of standards. Major browsers CSS prefixes are:

  • Chrome: -webkit-
  • Firefox: -moz-
  • iOS: -webkit-
  • Opera: -o-
  • Safari: -webkit-

Example:

.sample-output {
    -webkit-box-shadow: inset 0 0 1px 1px #eee;
    -moz-box-shadow: inset 0 0 1px 1px #eee;
    box-shadow: inset 0 0 1px 1px #eee;
}

Property Values

There are numerous ways to input values for properties. Adhere to specific ways uniformly across styles to bring consistency throughout the application.

  • For numerical values prefer ems instead of pixel values, more details here .
  • Properties Values pair will have a colon and space as separator. Hence values begin with space and should end with semicolon.
  • Use double quotes rather than single quotes for specifying values when needed.
  • Prefer numeric values for font weights to differentiate and measure the element styles (e.g. 400 instead of normal, 700 rather than bold).
  • 0 in values should not have units unless necessary, such as with transition-duration.
  • Use a leading zero for decimal values, including in rgba().
  • Line height should also be unit-less, unless necessary to be defined as a specific pixel value. This is not just convention but when used with units may not get the intend results, more details here .
  • Multiple comma-separated values for one property should be separated by either a space or a newline. - Multi line values should be indented one level in from the property.

Correct:

.selector1 { /* Correct usage of quotes */
    font-family: "Segoe UI Emoji", sans-serif;
}

.selector2 { /* Correct usage of font weight */
    font-weight: 300;
}

.selector3 { /* Correct usage of line height */
    line-height: 1.4;
}

.selector3 { /* Correct usage of zero values */
    margin: 0 1em;
}

.selector4 { /* Correct usage of short and lengthier multi-part values */
    font-family: Consolas, Monaco, monospace;
    transition-property: opacity, background, color;
    box-shadow:
        0 0 0 1px #5b9dd9,
        0 0 2px 1px rgba(30, 140, 190, 0.8);
}

Incorrect:

.selector1 { /* Avoid missing space and semicolon */
    margin:0
}

.selector2 { /* Avoid adding a unit on a zero value */
    margin: 0px 0px 20px 0px;
}

.selector3 {
    font-family: Times New Roman, serif; /* Quote font names when required */
    font-weight: bold; /* Avoid named font weights */
    line-height: 1.4em;
}

.selector4 { /* Incorrect usage of multi-part values */
    text-shadow: 0 1px 0 rgba(0, 0, 0, 0.5),
                 0 1px 0 #fff;
    box-shadow: 0 1px 0 rgba(0, 0,
        0, 0.5),
        0 1px 0 rgba(0,0,0,0.5);
}

Structure

Structuring the style sheet, with being enough clear to read will enable the fellow developers to have a clear understanding of the user interface document under construction. Hence its important to structure the style sheet.

  • Selector name should end with comma or opening curly brace in a single line. It should not be followed by other selector.
  • The closing brace should be flush left, using the same level of indentation as the opening selector.
  • Each property for the selector should be its own line. Property-value pairs should have at least one tab of indentation from the selector hierarchy and should end with semicolon.
  • Add lines to differentiate the sections. At least add two blank lines between sections and one blank line between blocks in a section.
  • Use only tabs for indentations to make spacing easy and simple.

Correct:

#selector-1,
#selector-2,
#selector-3 {
    color: #fff;
    text-align: center;
}

Incorrect:

#selector-1, #selector-2, #selector-3 {
    color: #fff;
    text-align: center;
    }

#selector-1, 
#selector-2 { color: #fff;
    text-align: center;
    }

#selector-1 { background: #fff; color: #000; }

Media Queries

Media queries supports identifying various characteristic of the user agent and its device, more details here. Media queries in general, addresses different features of the underlying user agent and its device, that provides flexibility to enable responsive design in our application, for various devices. When writing styles for an element consider writing them supporting responsiveness and multiple devices, using media queries. If we are adding any, be sure to test its purpose and its effects on the application.

  • It is generally advisable to keep media queries grouped by media at the bottom of the style sheet.
  • Rule sets for media queries should be indented one level in.

Example:

@media all and (max-width: 768px) and (min-width: 576px) {

        /* Your selectors */
}

Prefer using the media query to differentiate between touch and non-touch devices for the features, that has common functionality across all sizes of touch devices, rather using media queries on based on size of the devices.

Usage:

/* media query to target all non touch devices desktop/laptop */

@media not all and (pointer: coarse) {
}

/* media query to target for all touch devices */
@media (hover: none), (pointer: coarse) {
}

Additional details are provided here supporting the above mentioned media query that target touch and non touch devices.

Commenting

Feel free to comment liberally, comments should explain the brief intent for writing the specific selector, section or block. Long comments should manually break the line length at 80 characters. Inline comments should not have empty newlines separating the comment from the item to which it relates.

For sections and subsections:

/**
 * #.# Section title
 *
 * Description of section, whether or not it has media queries, etc.
 */
.selector {
    top: 0;
}

For inline:

/* This is a comment about this selector */
.another-selector {
    position: relative;
    top: 0 !important; /* I should explain why this is so !important */
}

Usage of SCSS

CSS on its own will help to achieve the required UI design and functionality. But for enterprise or large scale applications the style sheets may become much more larger, complex and harder to maintain. This is where we can use pre-processors for style sheets. SASS & SCSS are most commonly used pre processors, where SASS is similar to writing YAML files, where indentations are important, SCSS is similar to writing CSS. Do note that pre processors requires additional configuration to be added to the project to enable its support, that depends on the framework used for the development.

Pre processors lets us to use features that don't exist in CSS yet like variables, nesting, mixins, inheritance that would allow us to design our CSS rather than merely writing CSS for our elements. Below are few tips that will help in using SCSS.

  • Use simple SCSS features that can be understandable, maintainable.
  • Avoid using complex mixins, split the mixins to a simpler structural format rather to have complex single mixin.
  • Use meaning variable names that can be understandable by others for reusing the same.
  • Create variables, extendable properties at the common CSS files, avoid its creation at random instances in the files. This would allow developers to look for its availability at a location rather searching for the same. At instances if not possible to write in common CSS files, create them at the start of the files such that others can refer them for reusing.
  • Create colors, fonts, layouts etc that is common across the application in a variable for reusing purpose. Look for the same whether already been created before creating one.
  • Avoid using complex features like map, iterations of SCSS as possible as can.

The common features of the SCSS that can be used while designing CSS are listed below,

  1. Variables
  2. Nesting
  3. Import
  4. Mixins
  5. Extend/Inheritance
  6. Operators

The documentation will help to understand features of SCSS and its usage in depth.

Add on

It is often difficult to remember all the above mentioned standards and practices when writing CSS for our app, unless we do it regularly. Most of the IDE's support extensions and customization on the extensions, that takes care of updating the styles we wrote, to the necessary standards. Formatting CSS in this way to the standards, will make developer's life much more easier.

For e.g: IDE IntelliJ (2019+) version internally has SCSS lint and CSS Reordering plugins installed to it. In order to customize alignment, spacing, reordering on this extension, In intellij open settings (ctrl+alt+s) →editor →code style → style sheets → SCSS. After the settings are altered and saved, select all the styles or a block of styles in scss file, press alt+ctrl+shift+L to align and update the code to the standards.

That concludes the article. Hope this article threw some light on standards and best practices that can be applied while writing CSS.