Es una ilustración de Luke, el dev que escribió el artículo.
Development / October 8th 2020

Write better CSS to improve your code quality

Lucas Romero Di Benedetto's profile picture
byLucas Romero Di Benedetto

The problem 🙈

  • Unorganized properties in a CSS selector
  •  Sometimes, every developer writes code according their own rules and preferences
  • Hard to maintain
  • Code smells
  • Bad code quality

Approach 👀

  • Organize the CSS properties
  • Separate CSS properties into categories
/* Concept */
.selector {
  /* layout */
  /* position and dimensions */
  /* margin and padding */
  /* box enhancements */
  /* font enhancements */
  /* others */
}



Advantages 🙌

  • Better readability across devs and teams
  • Avoid possible redundant code
  • Easy refactoring
  • Easy to find some property
  • Easy to explain
  • Better code quality

Examples

The wrong way 🤢

The following is a really bad example, it works of course, but you need to avoid this type of code because it is hard to read and maintain. When you write code like this you are dropping the quality of your code and you are spreading bad practices to your teammates.

/* Avoid coding like this*/

.myBadClass {
  font-family: sans-serif;
  font-size: 22px;
  background-color: silver;
  border: 1px solid gray;
  box-shadow: 0 0 3px 20px black;
  display: flex;
  margin-right: auto;
  margin-left: auto;
  padding: 20px;
  margin-bottom: 30px;
  overflow: hidden;
  width: 100%;
  height: 50px;
  top: 0;
  border-radius: 7px;
  flex-direction: column;
  justify-content: center;
  cursor: crosshair;
  align-items: center;
  color: black;
  line-height: 1.5;
  position: relative;
}


The best way 😎

The following is a better way to write CSS, because it is better structured and easy to read. Just start proposing good practices so that your teammates also acquire them.

/* Do this way */

.myGoodClass {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  position: relative;
  top: 0;
  width: 100%;
  height: 50px;

  margin-left: auto;
  margin-right: auto;
  margin-bottom: 30px;
  padding: 20px;

  background-color: silver;
  border: 1px solid gray;
  border-radius: 7px;
  box-shadow: 0 0 3px 20px black;

  font-family: sans-serif;
  font-size: 22px;
  color: black;
  line-height: 1.5;

  overflow: hidden;
  cursor: crosshair;
}



If you have a small set of properties you can follow the pattern below.

.myOtherGoodClass {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  color: black;

  overflow: hidden;
}



Feedback 👂

  • What do you think about this practice?
  • How do you write better CSS?
  • Are you considering applying this on future projects?
  • If you don't agree with this pattern. Why not?
  • Do you have other ways to keep writing better CSS?