April 27, 2012

Best-practice approach to reset CSS styles on a specific element?

Question by shackleton

I’m building an html5/js/css application that will exist inside of a div on my client’s existing html. I want to be sure that none of the client’s CSS styles are inherited by my app.

Is there a best practice to reset this div and its descendant elements?

I’m thinking I’ll use something like:

#my-id * { //styles }

I’m wondering if there is a better/best-practice approach? Thanks.

Answer by Faust

That will be very difficult/likely impossible to ensure. The type of solutions that Ben Roux is referring to (update: Ben removed his answer, but this is now Starx’ answer) assume no preset styles other than the browser defaults, and “reset” in that context refers to harmonizing the inconsistencies across various browser defaults.

But in your case, your client CSS may already contain highly specific selectors such as

#someDiv .aClass a{float:left;}

… and applying those “CSS reset” solutions simply will not override this.

You can see that Truth’s selectors also have lower specificity than this, and therefore will fail to ovetride the client’s styles in such cases.

Your question is very similar: How to remove all inherited and computed styles from an element?

So the short answer is: there is no way to ensure this because you cannot “remove all inherited and computed styles from an element” … update: …unless you can anticipate and override every preexisting style declaration with new declarations having appropriate specificity.

Answer by Starx

You are probably looking for Eric’s CSS Reset as it one of robust resets out there.

But the reset rule is applied to the whole page, instead of the just the box. SO, modify the rules, by keeping #my-id infront.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!