Home > OS >  What is the best approach when you have 2 rules in CSS with the exact same properties except for one
What is the best approach when you have 2 rules in CSS with the exact same properties except for one

Time:09-24

Let's say you have these two rules:

.box1 {
        padding: 1.5em;
        margin: 1rem;
        
        color: rgba(0, 0, 0, .8);

.box2 {
        padding: 1.5em;
        margin: 1rem;
        
        color: rgb(71, 131, 250);   

And you really need each one to have its respective color.

My question is:

Is the next code a correct approach?

.box1, .box2 {
        padding: 1.5em;
        margin: 1rem;
        
        color: rgba(0, 0, 0, .8);
} 

.box2 {
        color: rgb(71, 131, 250);
} 

CodePudding user response:

Since those are classes, I actualy think you could have just one class, .box, for example, with all those properties, and then .box2 with the custom color.

.box {
        padding: 1.5em;
        margin: 1rem;
        color: rgba(0, 0, 0, .8);
} 

.box2 {
        color: rgb(71, 131, 250);
}

A straight answer to your question would be: yes. You have the correct approach. Always try to write as less code as possible.

EDIT: as pointed out in the comments by ray, in case I was not clear, you will apply both classes when you can to alternate color, as such:

<div class=“box box2”>
  • Related