Chrome Extension - Prevent CSS From Being Over Written - css

I am writing a Chrome Extension where a small panel appears on top of the existing website. When I go to certain websites, I notice that the CSS of my panel has been over-written by the website's CSS. I am currently using Eric Meyer's CSS Reset but it does not seem to be doing the trick. Is there something else I can do?

Here's a nifty 'hack' with iframes, where you don't actually instantiate an iframe:
Append an iframe to the DOM, this will be a container for your do dad
Walk into the iframe and add your HTML code to the innerHTML of the body
It looks like this:
var iframe = document.createElement('iframe');
document.documentElement.appendChild(iframe); //fastest way to append to DOM: http://jsperf.com/insertbefore-vs-appendchild/2
iframe.contentDocument.body.innerHTML = 'Normal link!!';

I'm not familiar with Chrome extensions themselves. But you could try scoping your panel within an 'id':
<div id='my-panel'>
PANEL GOES HERE
</div>
And then in the CSS just have #my-panel as the first selector for all of your css. Take the reset css and add the #my-panel identifier to each element defined there too. Might be tedious... but would ensure you're resetting all of your elements, and virtually guarantee that they'll be reset at a higher priority than anything the website might be defining.

An extension that I just wrote ran into similar problems. I've made most of them disappear, but not all of them. I think that I know why, but I haven't gotten around to fixing the exceptions (this is just a school assignment as of now).
Here is what I found: when a stylesheet is injected through the extension manifest or by the background page, it is treated as a user stylesheet, giving it cascade priority over the default browser stylesheet only. Adding !important directives to your rules will not help, at least in my experience. User stylesheets (added by an extension or manually) can contain !important directives, but they are not honoured by Chrome for some reason -- just check how they show up in the Chrome DevTools, without !important. Adding id attributes won't help either, as specificity will only trump where priority is equal otherwise.
What does work for me:
var ninjaCSS = document.createElement("link");
ninjaCSS.setAttribute("rel", "stylesheet");
ninjaCSS.setAttribute("type", "text/css");
ninjaCSS.setAttribute("href", chrome.extension.getURL('ninja.css'));
document.getElementById("head").appendChild(ninjaCSS);
This code is included in a JavaScript file that is listed in the manifest as a content script, and should run at document load. The CSS file is not listed in the manifest, but is included in the extension folder. Now the stylesheet is on an equal footing with the the other author stylesheets.
Of course, that is just the beginning. You can now give all elements in your panel an id attribute (you probably already have). Whether you use a style reset or not is up to you. But you will have to make sure that your styles specify every single rule that a stylesheet in the wild might try to manipulate. If you do not plan to change a rule from its default, you must still specify that default value. Even if the default value is "none";
Finally, you must bravely ignore all warnings that the !important directive is best used sparingly. Quite the opposite applies here. When you add !important to every one of your style rules, it will be as if you had not used it at all as far as your panel's cascade is concerned. On the other hand, you will now be the boss of your panel. Trust me, somebody is going to tack an !important directive on, say, their button:hover background-image rule. Leading your well-crafted buttons to inexplicably morph into concert images of a 1985 bon jovi concert -- but only when the mouse is hovering, so no worries, right?

appendChild solutions works for me (Devin G Rhode and jCyCle answers). But I noticed these solutions just add the attribute xmlns="http://www.w3.org/1999/xhtml". So I tested my code just by adding this xmlns attribute to my link tag (directly, not using JS) and it works too, don't know why.
Failing:
<link rel="stylesheet" type="text/css" href="filesystem:chrome-extension://................/temporary/Content/Styles/style.css" />
Working:
<link xmlns="http://www.w3.org/1999/xhtml" rel="stylesheet" type="text/css" href="filesystem:chrome-extension://.............../temporary/Content/Styles/style.css" />

Related

Blazor ignoring scoped CSS in Components

I have a similar problem as mentioned here.
The component MyComponent.razor has the scoped CSS MyComponent.razor.css.
Anyways, the style of the CSS file SOMETIMES is ignored. If I change the CSS it might work on the first start, or it might happen that I have to build the project 10 times before it works. If I move the Component (including the scoped CSS) from one folder to another and move it back, it is more likely to work as well.
It is also not a caching issue. When I hard refresh the browser and clear the cache, the CSS is still not loaded. In the dev tools, I am also not able to find the specific changes in the bundled CSS. E.g., if in the CSS I simply change the background-color of a class from blue to red, the background-color is still blue in the bundled CSS.
Within my _Host.cshtml the bundled style is added.
<head>
...
<link href="<applicationName>.Client.styles.css" rel="stylesheet" />
</head>
Project.Client.csproj does not contain a
<RazorLangVersion>3.0</RazorLangVersion>
The issue was relatively hard to find, but I found the solution. The problems I faced were caused by the components themselves. Basically, my Pages/Components look something like this:
<MyComponentA></MyComponentA>
<div>
<MyComponentB></MyComponentB>
<MyComponentC class="customCssClass">
<MyComponentD></MyComponentD>
</MyComponentC>
</div>
To make styling work, I need to pass down the style with the ::deep CSS-Keyword. Otherwise, the style is not passed down to the component. This means, my CSS looks something like this:
::deep .customCssClass {
}
Keep in mind, that ::deep needs to be added to every CSS class, otherwise, it doesn't work (at least it didn't for me).
Another issue is that I found that under certain circumstances it still didn't work for some components. I honestly have no idea which part of my code breaks it, but the fix was to wrap the entire Page/Component into a div. My code from above would look something like this then:
<div>
<MyComponentA></MyComponentA>
<div>
<MyComponentB></MyComponentB>
<MyComponentC class="customCssClass">
<MyComponentD></MyComponentD>
</MyComponentC>
</div>
</div>
TLDR: Add ::deep to every CSS element and wrap the page/component into a div.

How to find CSS element from Inspect in the actual source files?

I had a question on how to find out which part of your code needs changing to adjust this "display:none !important" functionality which prevents the website to be responsive on mobile. When going under 767px content simply disappears and that condition triggers.
If I change it to "display:inline !important" that works but I've only done it in-browser and I can't find where to change it in the source files. Is there any methodology on finding this out? I've even used grep on all the files in the theme looking for keywords but I don't know where else to look. Also tried adding the changed code into the "Additional CSS" menu however with no success either.
The question is:
Is there any methodology to finding this [where the CSS lives] out?
You want to know the methodology to find the CSS. Let's walk through how I did it.
Step 1
The inspector gives you the location of the styles. Using your images, I marked the locations with the red boxes:
Notice that the style in question is located in (index):557. Where is that? It's not an external stylesheet, as with the style.css example. Rather, it's been added directly into the <head> and wrapped in <style>.
Using Dev Tools, look in the <head> of the DOM (in the HTML markup). You'll find it there.
Step 2:
Where do you find it? The method that I use is to look at the style declarations first in the <head>. Are there any comments to give you clues?
Next, I look at the actual style attributes. In this case, it's .tm_pb_builder. That is giving you a clue to the component that builds the CSS.
I did a Google search for that class attribute, like this: wordpress tm_pb_builder. That took me to GitHub and the Power Builder plugin from TemplateMonster.
Step 3
Now you know that the plugin Power Builder is the one responsible for adding that style into the <head>. You can then take a look at the respective page and explore how this page is built with this page builder.
That's my methodology.
You can add display:inline !important in the style.css of your child-theme, but it will only works if the plugin css file loads before it.
If the theme's css loads before plugin css, you can create a new css style and enqueue it at the very last end of the style enqueue.
add_action('wp_enqueue_scripts', 'se_41042975', 999);
function se_41042975(){
wp_enqueue_style('css-plugin-override', get_stylesheet_directory_uri(); ?>/css/custom_css.css');
}
Hope it helps!

Selecting objects within a class

So, this is a question that's been nagging at me for a long time. I've been digging much more into CSS these days. I'm trying to stay away from jQuery for this project as it's in Drupal and I'm trying to stay away from custom code.
So, we have a class the system applies to BODY called "not-logged-in" when the user isn't logged in. Now this should work well for us (as I understand CSS), as we're only allowing admins to "log in". We are having collisions when we have someone editing a node -- all our custom classes are loaded in both cases and some of the editing controls are looking funky because of it.
So the BODY style is something like this:
<body class="html not-front not-logged-in no-sidebars page-node page-node- page-node-1 node-type-page footer-columns" >
... [much body content here--other divs, other classes, elements with IDs] ...
<div class='mycustomclass'>Should be bigger if logged in</div>
</body>
So, when I try to add a CSS selector and style, like this:
.not-logged-in .mycustomclass {
font-size: 20px;
}
It seems to ignore .mycustomclass. I've run into this before and chalked it up to my poor CSS-fu. And there was always jQuery, so I really didn't have to care. I'd really appreciate it if someone could clear this long-time mystery up for me.
Your syntax is fine, no problems there.
I imagine one of two problems:
The class is not actually being loaded, either on the body, or on your mycustomclass element. Check both in the rendered source (i.e. in the browser), not just your own code. As it's Drupal, it could be caching so your changes are not being loaded. Clear the Drupal cache.
Specificity. Perhaps there is another class on the element, or perhaps there's a global rule. Either way, something could be overriding your CSS on that element.
To solve both, use Firebug and the Web Developer Toolbar in Firefox. Both are essential for doing CSS.
Be sure that Drupal is adding the css script tags in the <head> of your HTML. You should have them follow after your stylesheet references. That's it, the drupal css (the one that is adding the not-logged-in class to the <body>) must execute before your css.

What's so bad about in-line CSS?

When I see website starter code and examples, the CSS is always in a separate file, named something like "main.css", "default.css", or "Site.css". However, when I'm coding up a page, I'm often tempted to throw the CSS in-line with a DOM element, such as by setting "float: right" on an image. I get the feeling that this is "bad coding", since it's so rarely done in examples.
I understand that if the style will be applied to multiple objects, it's wise to follow "Don't Repeat Yourself" (DRY) and assign it to a CSS class to be referenced by each element. However, if I won't be repeating the CSS on another element, why not in-line the CSS as I write the HTML?
The question: Is using in-line CSS considered bad, even if it will only be used on that element? If so, why?
Example (is this bad?):
<img src="myimage.gif" style="float:right" />
Having to change 100 lines of code when you want to make the site look different. That may not apply in your example, but if you're using inline css for things like
<div style ="font-size:larger; text-align:center; font-weight:bold">
on each page to denote a page header, it would be a lot easier to maintain as
<div class="pageheader">
if the pageheader is defined in a single stylesheet so that if you want to change how a page header looks across the entire site, you change the css in one place.
However, I'll be a heretic and say that in your example, I see no problem. You're targeting the behavior of a single image, which probably has to look right on a single page, so putting the actual css in a stylesheet would probably be overkill.
The advantage for having a different css file are
Easy to maintain your html page
Change to the Look and feel will be easy and you can have support for many themes on your pages.
Your css file will be cached on the browser side. So you will contribute a little on internet traffic by not loading some kbs of data every time a the page is refreshed or user navigates your site.
The html5 approach to fast css prototyping
or: <style> tags are no longer just for the head any more!
Hacking CSS
Let's say you're debugging, and want to modify your page-css, make a certain section only look better. Instead of creating your styles inline the quick and dirty and un-maintainable way, you can do what I do these days and take a staged approach.
No inline style attribute
Never create your css inline, by which I mean: <element style='color:red'> or even <img style='float:right'> It's very convenient, but doesn't reflect actual selector specificity in a real css file later, and if you keep it, you'll regret the maintenance load later.
Prototype with <style> instead
Where you would have used inline css, instead use in-page <style> elements. Try that out! It works fine in all browsers, so is great for testing, yet allows you to gracefully move such css out to your global css files whenever you want/need to! ( *just be aware that the selectors will only have page-level specificity, instead of site-level specificity, so be wary of being too general) Just as clean as in your css files:
<style>
.avatar-image{
float:right
}
.faq .warning{
color:crimson;
}
p{
border-left:thin medium blue;
// this general of a selector would be very bad, though.
// so be aware of what'll happen to general selectors if they go
// global
}
</style>
Refactoring other people's inline css
Sometimes you're not even the problem, and you're dealing with someone else's inline css, and you have to refactor it. This is another great use for the <style> in page, so that you can directly strip the inline css and immediate place it right on the page in classes or ids or selectors while you're refactoring. If you are careful enough with your selectors as you go, you can then move the final result to the global css file at the end with just a copy & paste.
It's a little hard to transfer every bit of css immediately to the global css file, but with in-page <style> elements, we now have alternatives.
In addition to other answers.... Internationalization.
Depending of the language of the content - you often need to adapt the styling of an element.
One obvious example would be right-to-left languages.
Let's say you used your code:
<img src="myimage.gif" style="float:right" />
Now say you want your website to support rtl languages - you would need:
<img src="myimage.gif" style="float:left" />
So now, if you want to support both languages, there's no way to assign a value to float using inline styling.
With CSS this is easily taken care of with the lang attribute
So you could do something like this:
img {
float:right;
}
html[lang="he"] img { /* Hebrew. or.. lang="ar" for Arabic etc */
float:left;
}
Demo
Inline CSS will always, always win in precedence over any linked-stylesheet CSS. This can cause enormous headache for you if and when you go and write a proper cascading stylesheet, and your properties aren't applying correctly.
It also hurts your application semantically: CSS is about separating presentation from markup. When you tangle the two together, things get much more difficult to understand and maintain. It's a similar principle as separating database code from your controller code on the server side of things.
Finally, imagine that you have 20 of those image tags. What happens when you decide that they should be floated left?
This only applies to handwritten code. If you generate code, I think that it's okay to use inline styles here and then, especially in cases where elements and controls need special treatment.
DRY is a good concept for handwritten code, but in machine-generated code, I opt for "Law of Demeter": "What belongs together, must stay together". It's easier to manipulate code that generates Style tags than to edit a global style a second time in a different and "remote" CSS file.
The answer to your question: it depends...
Using inline CSS is much harder to maintain.
For every property you want to change, using inline CSS requires you to look for the corresponding HTML code, instead of just looking inside clearly-defined and hopefully well-structured CSS files.
The whole point of CSS is to separate content from its presentation. So in your example you are mixing content with presentation and this may be "considered harmful".
In addition to the other answers, another concern is that it violates the recommended Content Security Policy from MDN, https://infosec.mozilla.org/guidelines/web_security#content-security-policy
The justification they use is that inline javascript is harmful, XSS, etc., but it doesn't justify why inline styles should also be disabled. Maybe someone can comment as to why, but until then, I'll just rely on appeal-to-authority and claim: it's a security best practice to avoid inline styles.
Code how you like to code, but if you are passing it on to someone else it is best to use what everyone else does. There are reasons for CSS, then there are reasons for inline. I use both, because it is just easier for me. Using CSS is wonderful when you have a lot of the same repetition. However, when you have a bunch of different elements with different properties then that becomes a problem. One instance for me is when I am positioning elements on a page. Each element as a different top and left property. If I put that all in a CSS that would really annoy the mess out of me going between the html and css page. So CSS is great when you want everything to have the same font, color, hover effect, etc. But when everything has a different position adding a CSS instance for each element can really be a pain. That is just my opinion though. CSS really has great relevance in larger applications when your having to dig through code. Use Mozilla web developer plugin and it will help you find the elements IDs and Classes.
I think that even if you want to have a certain style for one element, you have to consider the possibility that you may want to apply the same style on the same element on different pages.
One day somebody may ask to change or add more stylistic changes to the same element on every page. If you had the styles defined in an external CSS file, you would only have to make changes there, and it would be reflected in the same element in all of the pages, thus saving you a headache. :-)
Even if you only use the style once as in this example you've still mixed CONTENT and DESIGN. Lookup "Separation of concerns".
Using inline styles violates the Separation of Concerns principle, as you are effectively mixing markup and style in the same source file. It also, in most cases, violates the DRY (Don't Repeat Yourself) principle since they are only applicable to a single element, whereas a class can be applied to several of them (and even be extended through the magic of CSS rules!).
Furthermore, judicious use of classes is beneficial if your site contains scripting. For example, several popular JavaScript libs such as JQuery depend heavily on classes as selectors.
Finally, using classes adds additional clarity to your DOM, since you effectively have descriptors telling you what kind of element a given node in it is. For example:
<div class="header-row">It's a row!</div>
Is a lot more expressive than:
<div style="height: 80px; width: 100%;">It's...something?</div>
Inline CSS is good for machine-generated code, and can be fine when most visitors only browse one page on a site, but one thing it can't do is handle media queries to allow different looks for screens of different sizes. For that, you need to include the CSS either in an external style sheet or in an internal style tag.
In-page css is the in-thing at the moment because Google rates it as giving a better user experience than css loaded from a separate file. A possible solution is to put the css in a text file, load it on the fly with php, and output it into the document head. In the <head> section include this:
<head> ...
<?php
$codestring = file_get_contents("styles/style1.txt");
echo "<style>" . $codestring . "</style>";
?>
... </head>
Put the required css in styles/style1.txt and it'll get spat out in the <head> section of your document. This way, you'll have in-page css with the benefit of using a style template, style1.txt, which can be shared by any and all pages, allowing site-wide style changes to be made via only that one file. Furthermore, this method doesn't require the browser to request separate css files from the server (thus minimising retrieval / rendering time), since everything is delivered at once by php.
Having implemented this, individual one-time-only styles can be manually coded where needed.
According to the AMP HTML Specification it is necessary to put CSS in your HTML file (vs an external stylesheet) for performance purposes. This does not mean inline CSS but they do specify no external stylesheets.
An incomplete list of optimizations such a serving system might do is:
Replace image references with images sized to the viewer’s viewport.
Inline images that are visible above the fold.
Inline CSS variables.
Preload extended components.
Minify HTML and CSS.
Personally, I think the hatred of inline css is just ridiculous. Hardcore cult behaviour, people just sheepishly repeat "Separation of concerns!". Yes, there are times where if there is a repeating element and you will need repeated styling to use a class targeted from a CSS file, but most of the time it improves speed of development and CLARITY OF CODE to put the style inline, it's great if I can look at the code and see that there is a custom margin height, it helps me picture the HTML document as a whole, instead of some named class that gives me little insight into which styles will be applied.
So I will be the contrarian here and say that inline css is great and that people who scream at you for using it are just following what they have been told without actually giving it any original unbiased consideration.
Even though I totally agree with all the answers given above that writing CSS in a separate file is always better from code reusability, maintainability, better separation of concerns there are many scenarios where people prefer inline CSS in their production code -
The external CSS file causes one extra HTTP call to browser and thus additional latency. Instead if the CSS is inserted inline then browser can start parsing it right away. Especially over SSL HTTP calls are more costly and adds up additional latency to the page. There are many tools available that helps to generate static HTML pages (or page snippet) by inserting external CSS files as inline code. These tools are used at the Build and Release phase where the production binary is generated. This way we get all the advantages of external CSS and also the page becomes faster.
In addition to other answers, you cant target the pseudo-classes or pseudo-elements in inline CSS
We have created a template-driven artifact generator that provides an include file capability for any kind of text artifact -- HTML, XML, computer languages, unstructured text, DSV, etc. (E.g., it's great for handling common Web or manual page headers and footers without scripting.)
Once you have that and use it to provide "style" tags inside your "head" tag, the "separation of concerns" argument goes away, to be replaced by "we have to regenerate after every change to the template" and "we have to debug the template from what it generates". Those gripes have been around since the first computer language to get a preprocessor (or someone started using M4).
On balance, we think the meta-izing capability of either a CSS file or "style" tags is cleaner and less error-prone than element-level styling. But it does require some professional judgment, so newbies and scatterbrains don't bother.

Prevent CSS resets only within a certain section of HTML

For the past few years, I've been developing sites with Eric Meyer's CSS resets. I love it and will never look back. I never even thought of looking back. But then today, we implemented a Telerik Rad Editor control. Unfortunately the CSS resets break the internal layout of the Rad Editor as well. Is there some way to prevent the resets from cascading down into the Rad Editor.
Thanks in advance.
We use the RadEditor extensively in our application, and have found similar issues with it. I've been working with the editor CSS code for almost 2 years now, and have found it to be fairly easy to overcome these issues.
Firstly, are you using a custom skin for the editor? This is the best way to overcome these issues. If you aren't you can simply add one by copying an existing theme and renaming it. This will allow you to modify the CSS in an external file, rather than trying to fiddle with overriding the stylesheet the is embedded in the Telerik assembly.
After that, it's going to be a simple matter of isolating which styles are causing the issues. I'm guessing from your comments that the buttons are not rendering correctly, most likely because your reset stylesheet is overriding the default list styles. I would use firebug to see where the reset file is overriding styles defined in the stylesheet.
Most likely it's because there is no style definition at all for things that are being reset, as anything defined in the Telerik stylesheets would be more specific than the reset styles, as they would contain a preceeding class name, which would increase the CSS specificity by 10.
If you could provide more specifics, I'd be happy to try to help more.
Hardly, as there are no "excluding" statements in CSS. You would have to re-introduce the things the reset stylesheet removes.
But from experience, I'm quite sure the reason for the screwup is just one or two things going awry. It may be possible to examine and fix them in reasonable time.
You could use an iframe to delineate the CSS contexts. But, it makes some things harder.
No. That's one of inherent problems with CSS reset.
That's a $1000 control?! Perhaps you should give them a call and request making it compatible with CSS reset.
Reset makes some deprecated attributes from Transitional HTML unusable, but "industry's best" editor shouldn't be relying on these. Everything else is fixable with appropriate stylesheet.
Actually, you can specifiy specific CSS files for the RAD Editor to reference when it loads up. Just create a CSS file that adds in what the reset takes away and only the RAD Editor will reference that CSS file.
For example this editor will refence a specific file called 'radEditor.css" when it loads on a page.
<telerik:RadEditor ID="RadEditor1" runat="server" AllowScripts="True">
<Content>
</Content>
<CssFiles>
<telerik:EditorCssFile Value="~/css/radEditor.css" />
</CssFiles>
</telerik:RadEditor>
Good luck, and hope this helps some.
You can find out what are the default values for the element (make an unstyled page with only the element and check with Firefox's DOM Inspector), then add the rules again at the end of your stylesheet with !important added to every rule.
If you're trying to work out the styles the elements started with you could refer to one of the popular browser's default stylesheets - for example, here's the WebKit one for HTML. I presume from the markup you can narrow it down to just a few elements?
Edit: Here's the Gecko one.
I'm just adding this here for reference. Twitter Bootstrap makes most of the buttons disappear. Here is the fix. The EditorCssFile is just used to change the background color of the editor back to white.
<style type="text/css">
.telerik img {
max-width:none;
}
</style>
<div class="telerik">
<telerik:RadEditor ID="RadEditor1" BackColor="White" ToolbarMode="RibbonBar" runat="server">
<CssFiles>
<telerik:EditorCssFile Value="/assets/css/editorContentArea.css" />
</CssFiles>
</telerik:RadEditor>
</div>

Resources