Search code examples
htmlcsscoding-stylestylesheet

Styles often occur in the same combination: Creating a single class or combining elements?


In one of my recent projects, I noticed that certain styles occur in the same combination repeatedly. According to the DRY principle, I should combine these styles. Regarding a good CSS style, what option is better/the best?

Option 1
Creating a class that contains these styles and simply add it in the HTML to the according elements.

Example

In the HTML:

<a href='#' class="myClass">Link</a>

or

<ul class="myClass">
  <li>Item</li>
<ul>

In the CSS:

.myClass {
  font-weight: bold;
  font-size: 14px;
  color: grey;
}

Option 2
Simply combining all elements that need that style in my CSS, like in the following example.

a,
ul {
  font-weight: bold;
  font-size: 14px;
  color: grey;
}

Solution

  • .myClass {
      font-weight: bold;
      font-size: 14px;
      color: grey;
    }
    

    is best ...

    .myclass {
      font-weight: bold;
      font-size: 14px;
      color: grey;
    }
    

    is even better (lower-case)

    This way, the DOM engine will get to the element without having to stack across all a and all ul tags in your document.