Search code examples
htmlcsscss-modules

How to have class styles override composed style in CSS Modules without using important?


I am using CSS Modules in my project and the composes command, like this:

// In one file

.btnSecondary {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-self: flex-end;
  padding: 12px 20px;
  border-radius: 8px;
}

// In another file

.btnInteract {
  composes: btnSecondary from "../buttons.module.css";
  align-self: flex-start;
  margin-bottom: 15px;
}

And then to my surprise in the compiled webpage, the align-self: flex-start; is overruled by the .btnSecondary class, as can be seen here:

enter image description here

I can fix this problem by just using !important in the btnInteract class, but I would rather not do that everywhere. Another might ask why I even have align-self: flex-end in the .btnSecondary class. Well, it's because 99% of the time that's what I want in the other class. Just not in this case.


Solution

  • CSS specificity hierarchy to the rescue!

    You can override existing styles by using more specific element description.

    .btnInteract {
      color: #deface;
    }
    
    // following selector is more important
    .parent .btnInteract {
      color: #FB1;
    }
    

    Easier solution for your problem is using id attribute rather than class. In this case id attributes are more important than class attributes from the browser perspective.

    Here is the link for the good article about this topic.