Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

oocss

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?

like image 724
catandmouse Avatar asked Oct 06 '22 02:10

catandmouse


2 Answers

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

like image 113
NielsInc Avatar answered Oct 10 '22 03:10

NielsInc


I personally would go with method 2. That way you can swap out text-red or text-green easily for text-blue or text-yellow and still keep the underlying style for your text. Basically, method 2 allows for more flexibility and maintainability, IMHO.

like image 29
Matt Whitehead Avatar answered Oct 10 '22 02:10

Matt Whitehead