DEV Community

Alex Carpenter
Alex Carpenter

Posted on

Improve your CSS with whitespace and comments

If I could share two things CSS developers can do to start improving their code, it would be to create more meaningful whitespace and add comments when necessary. Whitespace is a simple and effective way of documenting different parts of a CSS file. Check out the two examples below and let me know which one is easier to digest.

.o-table {
  width: 100%;
}
.o-table--fixed {
  table-layout: fixed;
}
.o-table--tiny {
  th, td {
    padding: $inuit-global-spacing-unit-tiny;
  }
}
.o-table--small {
  th, td {
    padding: $inuit-global-spacing-unit-small;
  }
}
.o-table--large {
  th, td {
    padding: $inuit-global-spacing-unit-large;
  }
}
.o-table--huge {
  th, td {
    padding: $inuit-global-spacing-unit-huge;
  }
}
Enter fullscreen mode Exit fullscreen mode

and below, a well documented, breathable CSS file

/* ==========================================================================
   #TABLE
   ========================================================================== */

/**
 * A simple object for manipulating the structure of HTML `table`s.
 */

.o-table {
  width: 100%;
}





/* Equal-width table cells
   ========================================================================== */

/**
 * `table-layout: fixed` forces all cells within a table to occupy the same
 * width as each other. This also has performance benefits: because the browser
 * does not need to (re)calculate cell dimensions based on content it discovers,
 * the table can be rendered very quickly. Further reading:
 * https://developer.mozilla.org/en-US/docs/Web/CSS/table-layout#Values
 */

.o-table--fixed {
  table-layout: fixed;
}





/* Size variants
   ========================================================================== */

.o-table--tiny {

  th,
  td {
    padding: $inuit-global-spacing-unit-tiny;
  }

}


.o-table--small {

  th,
  td {
    padding: $inuit-global-spacing-unit-small;
  }

}


.o-table--large {

  th,
  td {
    padding: $inuit-global-spacing-unit-large;
  }

}


.o-table--huge {

  th,
  td {
    padding: $inuit-global-spacing-unit-huge;
  }

}
Enter fullscreen mode Exit fullscreen mode

This code example is pulled from the inuitcss project.


This post was originally posted on my blog here.

Top comments (1)

Collapse
 
joshichinmay profile image
Chinmay Joshi

The second example looks better to me. It gives the precise idea of the style implemented for the class.
Some people prefer descriptive class names over comments. They want their file to be 'comment-less'.

Check out this video mdo-ular-css and website for more information about the best practices to write CSS. I follow his guidelines in my implementation.