Jo Sprague Jo Sprague - 1 month ago 4x
CSS Question

Best Practices for CSS Specificity?

I am creating a contact form that will be included on several different sites.

The styles of the contact form and the styles of the site will both be included and I can't very well predict the styles of the site. I want the styles of the contact form to be easily over-ruled by the styles of the site, but I don't want to styles of the contact form to be accidentally over-ruled.

For example, if the site developer wants to change the color of the submit button, it should be easily done without using

or some excessively specific
#id #id element .class #id element.class
type of selector.

But, on the other hand, if the site developer wrote styles using selectors like
input { background: yellow; }
#site-wrapper input { background: yellow; }
I don't want it to over-rule my contact form styles that refer to classes,
.contact_input { background: white; }

So my question is, what would the best practices be in this situation? I was thinking of putting an ID on my form and adding that to every selector, so my selectors would become
#contactform .contact_input { background: white; }
and I think that would work in terms of avoiding conflicts, but I'm wondering if there is a better way to do it, because that seems a little ineffecient in terms of page rendering. Maybe it's not a big deal, but I just thought I'd throw it out there and see what people think.


That's a quite hard cause both, the selector itself and its location in sheet do matter. Also the fact that there is no only one, true way of writing CSS doesn't help.

I guess it would be the best if you use ID and tag selector. Additionally use attribute selector:

#contact-form input { ... }
#contact-form input[type=email] { ... }
#contact-form select { ... }

However you should mention that it's strongly recommended to put that sheet on the top of others, eg:

<link type="stylesheet" href="/styles/contact-form.css" />
<link type="stylesheet" href="/styles/main.css" />

Why that approach?

Usually a developer will want to forms look the same all over the website, that's why he will use tag name selector:

input  { ... }
select { ... }

These selectors are weaker that #contact-form input so they won't override anything. However sometimes it's necessary to override some rules so the developer will use #contact-form input selector which is pretty natural in such case.

If sheets has been attached as a recommendation says developer's styles will override yours, despite the fact that both have selectors with exactly same strength. That's why the location of the rules matter.