How to raise css rules priority for an html snippet
I wrote a HTML/CSS snippet that is included in some 3-rd party website.
But CSS rules of that website make my snippet look terrible. To keep the snippet's appearance I must use !important keyword, but it's horrible, I have to write this keyword for about 1000 times (besides such a code looks not v开发者_如何学JAVAery nice).I can also use inline CSS instead of external .css file, but it's not a solution too.So, how can I protect my css styles in some elegant way?The suggestion to use a div
with a unique ID is good. However, there is a chance that other rules in the host page's style sheet use !important
. Those rules would override yours, even if you use a unique ID.
Short of using an external document in an iframe
in the first place (which is not always possible), using !important
is the only 100% safe way that I can see.
Your snippet should be included inside an iframe
.
It's the usual way these "widgets for 3rd party sites" work.
If you use an iframe
, CSS from the parent document can't affect your "HTML/CSS snippet".
You can try enclosing your snippet inside a DIV with a unique id.
Then on your CSS for that snippet's style, include the id selector of the DIV for the items in your stylesheet.
The only way I can think of is to make the selectors more specific in some way. For example,
LI { color: red; }
LI.class { color: blue; }
<li class="class">I will be blue</li>
but you're really at the mercy of the 'rest of the CSS' you don't have control over.
I think your best bet is to put ID's and unique classes on all yoru stuff and spec the heck out of it. This is not great either though becuase you might WANT some of the 'rest of the CSS' to apply.
If you can't go with the iframe method, you'll need to figure out what level of specificity the parent page declarations have and beat that with your style declarations, keeping in mind that they'll still apply if you don't clear them. Otherwise, bring on the "!important"s!!! You may want to look for a clear.css or something as well that does this for you, as many sites offer this.
精彩评论