April 27, 2024
Breaking News

Golden Guidelines for Writing Clean CSS – SitePoint

npressfetimg-3660.png

The following is an extract from our book, CSS Master, written by Tiffany Brown. Copies are sold in stores worldwide, or you can buy it in ebook form here.

Golden Guidelines for Writing Clean CSS

As mentioned, there are some rules for writing clean CSS that you should try your best to avoid breaking. They’ll help you write CSS that is lightweight and reusable:

  • Avoid global and element selectors
  • Omit overly specific selectors
  • Use semantic class names
  • Don’t tie CSS too closely to markup structure

Let’s look at these one by one.

Avoid Global Selectors

Global selectors include the universal selector (*), element selectors such as p, button, and h1, and attribute selectors such as [type=checkbox]. Style declarations applied to these selectors will be applied to every such element across the site. Here’s an example:

button {
  background: #FFC107;
  border: 1px outset #FF9800;
  display: block;
  font: bold 16px / 1.5 sans-serif;
  margin: 1rem auto;
  width: 50%;
  padding: .5rem;
}

This seems innocuous enough. But what if we want to create a button that’s styled differently? Let’s style a .close button that will be used to close dialog modules:

<span .......

Source: https://www.sitepoint.com/golden-guidelines-for-writing-clean-css/