How to raise css rules priority for an html snippet - html

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 very 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.

Related

how to prevent styling overlap

I'm building an app with many different components and I've run into an issue where styling from one component has overlapped with styling from another component. Other than giving each paragraph tag it's own class, is there anyway to prevent this? Say with a keyword or something?
Try to use as a specific selector as possible in your CSS file. It isn't just .class or #div. When you find a more specific selector you can always add !important after all your style.
It will have a higher importance level than everything else, but you can still change it from a different file if you use the same level.
This can be something like this:
.some-div > p {
font-size: 16px !important!
}
Please check this https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors for selectors.
I don't think there is any other way than giving unique class to every element.
Let me elaborate:
If you have used a web framework, say NextJs, you will see that it assign a unique class to every element to avoid class collision within page. And Styling IS one of them.
So yeah, Having unique classes IS necessary to avoid css collision, unless you don't go for an ID approach.

How to debug CSS specificity problems?

I've developing an app with Vue, and a third-party template, and dynamic plugins, and all kinds of trickery. I'm have a really hard time with the CSS.
Often I need to style particular element on the page, an <input> for example, and I can't figure out how to write a selector that actually works. The input may have been created dynamically by some Javascript and may have had CSS applied programmatically.
So I go to Firefox Web Developer, click on the element, and see a bunch of CSS classes. I create a rule:
.myCustomClass {
color: red;
}
put myCustomClass in the class="" tag in the <input>, and... nothing.
I'm thinking I need to prefix it like this:
.someOuterClass .someInnerClass .myCustomClass {
color: red;
}
but that rarely works. Sometimes I give up and add !important. Sometimes that works, and sometimes it doesn't.
So my question is, can I examine the classes that I can see in Web Developer and somehow derive a rule that is specific enough that it will always work?
I've read about specificity, but it's not helping.
Specificity is a PITA sometimes, especially when other 3rd party libraries are adding stuff to the mix.
Here are a few things you can try:
Make sure to add your styles to the END of the CSS. Theoretically, you can affect the order Webpack includes CSS (I've never tried it)
Add an ID not a class to a wrapper outside the elements you want to change. Then reference this ID in the CSS chain eg: #myAppID .className .subClassName {} Basically ID's are stronger than classes in CSS specificity. I would try to do this at a page/view level to make life easier.
If elements are already getting classes (as you see them in the inspector) try to reuse those classes with your "override" CSS. If the classes are modularized (Have a random suffix like someClass__34xft5) you shouldn't use those exact classes since they can change if the source is recompiled. In that case, use a "matching" selector [class^=”someClass__”] to match any selector with that prefix.
Not sure how deep you want to go, but here's an article about overriding Amplify-Vue prebuilt styling.
One caveat, if the CSS is being added inline via javascript somewhere, it's going to be very hard to override. You may want to use !important in conjunction with the above.
"...can I examine the classes that I can see in Web Developer and somehow derive a rule that is specific enough that it will always work?"
Probably, but why bother? You're already adding class attributes to elements. Why not add inline style attributes instead? Adding a bunch of classes or ids just to create a specificity chain to touch up styles is pretty messy...inline styles are barely if at all worse and are clearer to understand.
Inline attributes are the most specific CSS instructions you can give.

More important than !important (a higher level !important)?

The title says most of it. Is there a CSS keyword which overrides !important at one higher level or is there some feature like this planned in any newer CSS spec?
Of course, I know that !important is a bit likely to be used by noobs and that in many cases it is not the best way to go as stylesheets may really suck if badly written. However, sometimes it's useful and even needed.
The strongest style in CSS I can think of is an inline style with !important like this:
<span id="bluebeaver" style="color: red !important;">I am a happy blue beaver</span>
Now let's assume that I cannot edit the HTML and must modify the style from an external stylesheet.
It would be really great to have something like:
#bluebeaver {
color: blue !important 2;
}
If they had levels for it like for instance with z-index.
Is there any solution to this or anything planned with newer CSS specifications?
So far I did not find anything.
Can you show a CSS solution to override an !important inline style or is there definitely no possibility?
Simply remove the style attribute from the element using JavaScript:
document.getElementById("bluebeaver").removeAttribute('style');
Then use your external stylesheet to apply whatever CSS you want.
Two reasons why creating higher levels of !important is not a good idea:
It sets a bad precedent.
Adding !important2 would be caving in to poor-coding habits on a global scale. It would be the W3C sending a signal that anything goes.
You've also opened the door to !important3, !important4, etc. Where does it end?
Lowering standards and expectations is not a good way for the industry to make progress.
It may not even solve your problem.
Consider this: The person who set that inline style to color: red !important, obviously wanted that rule to have the highest priority.
If your idea became real, and there were higher levels of !important, let's say going up to !important10, guess what that person would have used? And you'd still have the same problem, but you'd be here asking if there were any plans for !important11.
No, there is no keyword or other way to make a declaration more important than !important. There is no known activity to change this.
In general, it is possible to override a declaration that has !important by using a rule that also has it and that has higher specificity. However, a declaration in a style attribute has, by definition, higher specificity than any other author declaration. The only way to defeat it is in CSS is to use a user style sheet with !important.
There are non-CSS solutions, but they are rather obvious, such as using JavaScript to simply remove or modify the style attribute.
The highest order I know of is targeting elements that have inline styles applied. You can actually select the element's style data attribute in the CSS selector to override its style! Check this out:
.blue[style]{
color:blue !important;
}
<div class="blue" style="color:red;">SO VERY IMPORTANT</div>
Of course you can even get more specific by targeting the style specifically, such as .blue[style="color:red;"].
You can modify the colour of HTML element using javascript.
document.getElementById('bluebeaver').style.color=blue;
Demo : https://jsfiddle.net/041fhz07/
Try Specificity: If two selectors apply to the same element, the one with higher specificity wins.
Try to style your element the more specific you can. Maybe use:
#bluebeaver span {}
Take a look to this link: CSS Specificity: Things You Should Know
if you want to use CSS only you just declare the new style with !important, the last "important" wins. though I'd avoid using it in the first place unless completely necessary.
it should only be used for styles that are essential for your page/app to work, not things that are expected to change.
another solution is to use JS to remove and/or add classes/id to change the style of the element when you don't want to change the CSS itself.
div.prop1.imp1.imp2 {
background-color: red !important;
}
div.prop1 {
background-color: black;
}
div.prop1.imp1 {
background-color: white !important;
}
If you can't do this since not all elements have the .imp1 class on the list in JavaScript, and you are adding say a highlight on something with a button click (.imp2) . You can specify the 'more important' .imp2 class above the others with !important on it.
This makes the property with the additional imp2 class more important than the .prop1.imp1 style because it is loaded first in the css.

When to use the !important property in CSS [duplicate]

This question already has answers here:
What are the implications of using "!important" in CSS? [duplicate]
(9 answers)
What does !important mean in CSS?
(5 answers)
Closed 4 years ago.
Consider:
#div p {
color: red !important;
}
...
#div p {
color: blue;
}
I understand how !important works. In this case the div will render red because now it has priority (!important). But I can't still figure out an appropriate situation to use it in. Is there an example where !important saves the day?
This is the real life scenario
Imagine this scenario
You have a global CSS file that sets visual aspects of your site globally.
You (or others) use inline styles on elements themselves which is usually very bad practice.
In this case you could set certain styles in your global CSS file as important, thus overriding inline styles set directly on elements.
Actual real world example?
This kind of scenario usually happens when you don't have total control over your HTML. Think of solutions in SharePoint for instance. You'd like your part to be globally defined (styled), but some inline styles you can't control are present. !important makes such situations easier to deal with.
Other real life scenarios would also include some badly written jQuery plugins that also use inline styles...
I suppose you got the idea by now and can come up with some others as well.
When do you decide to use !important?
I suggest you don't use !important unless you can't do it any other way. Whenever it's possible to avoid it, avoid it. Using lots of !important styles will make maintenance a bit harder, because you break the natural cascading in your stylesheets.
Overwriting the Style Attribute
Say in the example that you are unable to change the HTML source code but only provide a stylesheet. Some thoughtless person has slapped on a style directly on the element (boo!)
div { background-color: green !important }
<div style="background-color:red">
<p>Take that!</p>
</div>
Here, !important can override inline CSS.
This is a real, real life scenario, because it actually happened yesterday:
Z-index in jQuery dialog. Autosuggest list not displayed properly
Alternatives to not using !important in my answer included:
Hunting down in JavaScript/CSS where a certain elusive property was being applied.
Adding the property with JavaScript, which is little better than using !important.
So, a benefit of !important is that it sometimes saves time. If you use it very sparingly like this, it can be a useful tool.
If you're using it just because you don't understand how specificity works, you're doing it wrong.
Another use for !important is when you're writing some kind of external widget type thing, and you want to be sure that your styles will be the ones applied, see:
Appended control's CSS
You generally use !important when you've run out of other ways to increase the specificity of a CSS selector.
So once another CSS rule has already dabbled with Ids, inheritance paths and class names, when you need to override that rule then you need to use 'important'.
!important is somewhat like eval. It isn't a good solution to any problem, and there are very few problems that can't be solved without it.
I have to use !important when I need to overwrite the style of an HTML generated by some JavaScript "plugin" (like advertising, banners, and stuff) that uses the "style" attribute.
So I guess that you can use it when you don't control the CSS.
Strictly speaking you shouldn't need to use !important if you've structured your CSS well and don't have too many degrees of specificity.
The most appropriate time to use !important is when you have one exceptional style that you want to style outside of your site's normal cascade.
Using !important is generally not a good idea in the code itself, but it can be useful in various overrides.
I use Firefox and a dotjs plugin which essentially can run your own custom JS or CSS code on specified websites automatically.
Here's the code for it I use on Twitter that makes the tweet input field always stay on my screen no matter how far I scroll, and for the hyperlinks to always remain the same color.
a, a * {
color: rgb(34, 136, 85) !important;
}
.count-inner {
color: white !important;
}
.timeline-tweet-box {
z-index: 99 !important;
position: fixed !important;
left: 5% !important;
}
Since, thankfully, Twitter developers don't use !important properties much, I can use it to guarantee that the specified styles will be definitely overridden, because without !important they were not overridden sometimes. It really came in handy for me there.
The use of !important is very import in email creation when inline CSS is the correct answer. It is used in conjunction with #media to change the layout when viewing on different platforms. For instance the way the page looks on desktop as compare to smart phones (ie. change the link placement and size. have the whole page fit within a 480px width as apposed to 640px width.
This is a real-world example.
While working with GWT-Bootstrap V2, it will inject some CSS file, which will override my CSS styles. In order to make my properties to be not overridden, I used !important.
I'm using !important to change the style of an element on a SharePoint web part. The JavaScript code that builds the elements on the web part is buried many levels deep in the SharePoint inner-workings.
Attempting to find where the style is applied, and then attempting to modify it seems like a lot of wasted effort to me. Using the !important tag in a custom CSS file is much, much easier.
I am planning to use !important for a third-party widget meant to be embedded in a large number of websites out of my control.
I reached the conclusion !important is the only solution to protect the widget's stylesheet from the host stylesheet (apart from iframe and inline styles, which are equally bad). For instance, WordPress uses:
#left-area ul {
list-style-type: disc;
padding: 0 0 23px 16px;
line-height: 26px;
}
This rule threathens to override any UL in my widget because id's have strong specificity. In that case, systematic use of !important seems to be one of the few solutions.
You use !important to override a css property.
For example, you have a control in ASP.NET and it renders a control with a background blue (in the HTML). You want to change it, and you don't have the source control so you attach a new CSS file and write the same selector and change the color and after it add !important.
Best practices is when you are branding / redesigning SharePoint sites, you use it a lot to override the default styles.

How to get CSS file to affect only a section of HTML

I have an external CSS file (I cannot change it at all) which I need to use in my HTML file, but I want the CSS to only affect a section of my HTML. (For example everything in <div id="externally_styled"></div>)
How is this possible, again, without changing the CSS file (and the CSS file contains also general styles that affect body tags etc)
You'd probably have to use an iframe with a page containing only the HTML you want styled and a reference to the stylesheet. This would mean the general styles wouldn't be applied to the containing page, but it sounds like that's what you want.
Any classes or style-declarations attached to a tag will override the declarations in the CSS-file.
Just add your own style-declaration to a tag:
<div style="<your own declarations>">
...
</div>
You can overwrite the general styles that you don't want to be applied to your HTML document. This may be a good idea if the CSS if not that extensive.
The way to overwrite an style is using the keyword important!.
e.g:
original stylesheet:
body {
color: #000000;
}
your stylesheet:
body {
color: #CCCCCC !important;
}
You can find more information here.
I'd guess any client side solution is going to be messy.
Can you use a server side solution where you suck in the external CSS file and append a class selector to the start of each rule? I'm sure this would be easy enough with regex.
One way that springs to mind is to have the "to-be styled" portion of your HTML exist in a completely separate file and then pull it in via an iframe that uses the CSS from the external file.
The only thing i can think of is to re-render the content from your DIV to an Iframe.
Either use classname of the class that you have created for your specific section or use proper parent child relationship css that will render only when it falls under the parent child relationship.
You can enforce style by using "!important" in your css codes.
take a look at this example.
http://www.craiglotter.co.za/2010/01/21/important-css-how-to-force-one-style-above-another/