hughmanwho hughmanwho - 9 months ago 41
HTML Question

CSS: Is it possible to override one class with another?

I have a template class, that is simply:

display: none;

This allows me to create a block with html that I can clone using jQuery and slightly edit to my liking. However, one of the class I've been assigning to this same element to be cloned, sets:

//other properties not related to this problem not shown

This ends up overriding the template display property, which defeats the whole purpose of making it a template class.

Certainly I can always just add the Category class at the same time as I remove the template class via jQuery after cloning, but it's not ideal because the whole point is that the html should be easy to edit and changes can be made there instead of within jQuery code.

Thoughts? I'm thinking maybe I can tell display to override other properties or something like that?

Thank you!

Answer Source

CSS has a very well-defined order of priority.

If two selectors have the same priority (as per your two single-class selectors), then with all else being equal, the one which is defined last in the CSS code is the one that takes priority.

So the simple solution here is to move your template CSS to lower down your CSS code.

If you can't do that for whatever reason, your best option is to make the template selector more specific. For example, if all your template elements are contained inside a div element and you know that's always going to be true, you could change the selector to div .template. It is now more specific than the .Category selector, and should therefore take precedence.

Finally, you always have the option of !important. I try to avoid using it if possible, as it tends cause issues if overused, but it is there for cases where it's needed, and in fact, cases like this are about the best justified use-case for !important I can think of.