Search code examples
cssoocss

Is it better to chain CSS classes or name them separately for modular purposes?


For example, which is better:

Method 1 (name classes separately):

/* CSS */

.textbox-red, 
.textbox-green {
   padding: 10px;
   border: 1px solid #CCC;
   border-radius: 10px;   
}

.textbox-red { color: #900; }
.textbox-green { color: #3c3; }

/*HTML*/

<div class="textbox-red"></div>
<div class="textbox-green"></div>

OR ------------

Method 2 (chain classes):

/* CSS */

.textbox {
  padding: 10px;
  border: 1px solid #CCC;
  border-radius: 10px;
}

.textbox.text-red { color: #900; }
.textbox.text-green { color: #3c3; }

/*HTML*/

<div class="textbox text-red"></div>
<div class="textbox text-green"></div>

What is a better practice among the two?


Solution

  • My opinion is that you should use modular css - You could also combine classes instead of linking them:

    /*CSS*/
    .textbox {
      padding: 10px;
      border: 1px solid #CCC;
      border-radius: 10px;
    }
    
    .text-red { color: #900; }
    .text-green { color: #3c3; }
    
    /*HTML*/
    
    <div class="textbox text-red"></div>
    <div class="textbox text-green"></div>
    

    That way you can reuse the red and green colors in cases when you want to have a red background without a textbox. This way you can re-use your code more and you have a loose coupling between your textbox and text-color