Inject CSS with chrome developer tool? - css

Where can I add CSS to the page I'm viewing? I don't want to add style to one element directly, I want to add a 'document' to a page to debug changes before editing the site's style.css.
Note, there are lots of questions here about 'injecting CSS from a chrome extension', but specifically I want to do it via the 'Chrome Developer Tools' thingy.

I'm not sure if it works, but you'd have to try.
Pressing F12/ (Cmd + opt + I on Mac) to open up the Developer Console and go to the Console tab.
Copy paste the following code (edit the path):
$(document.head).append('<link rel="stylesheet" href="path_to_my_css">');
Alternatively, you could edit one property so the inspector-stylesheet.css is created by Chrome, and copy past your CSS source there.

There are multiple ways to do that, and they are also very easy.
First way, inspector-stylesheet:
Open Inspect Element (F12 Or Ctrl+ Shift+I)
Go to Elements tab (Ctrl+ Shift+ P and type show elements), if you are not already there, see the Styles tab, now see on right corner, there would be a + icon, click it (or long press that icon if it doesn't automatically add inspector-stylesheet), it will add selector of currently highlighted element, just next to the selector, there will a link/button inspector-stylesheet, click it, it will take you a window, where you can add styles.
Second way, Edit as HTML
Open Inspect Element (F12 Or Ctrl+ Shift+I)
Go to element panel (Ctrl+ Shift+ p and type show element panel).
Scroll to the head element right click on the element and choose Edit as HTML, go to the bottom of that element (Ctrl+ End), add your <style></style> element there add your style in that element, and hit Ctrl+ Enter.
Third way, Snippet:
Open Inspect Element (F12 Or Ctrl+ Shift+I)
Go to the Source tab, go to the Snippets tab, click on the + New snippet, name it whatever you want, and add this:
Create new snippet Ctrl+ Shift+ P type Create new snippet hit Enter , rename the snippet if you want to, and add this (edit the style) :
(function(){
let style = `<style>
/*change your style here*/
body{
display:none;
}
</style>`;
document.head.insertAdjacentHTML("beforeend", style);
})();
Save it, run it (Ctrl+Enter).
You can also run the snippets by doing this: Ctrl+ p type ! it will show your saved snippets, choose the one you want to run.
To edit or see your snippets, Ctrl+ Shift+ P type show snippets.
In FireFox it's even easier:
Open Inspect Element (F12)
Go to Style Editor, click the + icon and you will be able to edit the style; You can also, import styles, just by clicking the icon next to the +.

To begin with, this is one reason why I use Firefox for teaching and my own development work. The answer is built in.
As a variation to the above answers, using modern JavaScript, you can add a hard-coded style as follows:
document.head.insertAdjacentHTML('beforeend','<style> … </style>');
or you can add an external style sheet as follows:
document.head.insertAdjacentHTML('beforeend','<link rel="stylesheet" href="…">');
The beforeend argument is to help the injected CSS to override previously loaded styles.
If you’re going to do this repeatedly, you can then add it as a bookmarklet, using something like Bookmarklet Crunchinator.
The technique is similar to one I teach in a JavaScript class, where I use afterbegin to inject some default CSS, but allow user style sheets to override the defaults.

Why not a kind of simple framework agnostic one-liner like this?
document.body.appendChild(function() {var el = document.createElement('link'); el.setAttribute('rel', 'stylesheet'); el.setAttribute('href', 'http://domain/print.css'); return el;}())
Seems to work like a charm...

Since 2018 in Chrome (65) the browser's integrated DevTools has a feature called Local Overrides 1. As such, there is no need for an add-on or extension like StyleBot, Stylish or Greasemonkey.
Local Overrides allow rewrites of CSS, JS and DOM on any live site. Changes are saved in a local folder and they override the contents of the live environment.
This can be accessed under Developer Tools > Sources >> Overrides
This allows you to select a custom local folder that will contain CSS and JS that will override the current website's own CSS and JS.

This should work (paste into console, edit arguments in the last line as needed):
(function(i,n,j,e,c,t,css){
css=i.createElement(n);t=i.getElementsByTagName(c)[0];css.href=j;css.rel=e;
t.insertAdjacentElement('beforeend',css);})
(document,'link','//fonts.googleapis.com/css?family=Roboto','stylesheet','head');
This will insert a <link>
with an href //fonts.googleapis.com/css?family=Roboto
before the closing </head>
If there's no head tag in the document you're trying to add a css file to, try body as the last argument:
(document,'link','//fonts.googleapis.com/css?family=Roboto','stylesheet','body');

You can inject CSS using snippets in Chrome Devtools. Save and execute the snippet and then invoke it in the console or in another snippet:
function insertCss(code) {
var style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) { // IE
style.styleSheet.cssText = code;
} else { // Other browsers
style.innerHTML = code;
}
document.getElementsByTagName("head")[0].appendChild( style );
}
// run the snippet as follows:
insertCss('span { color: red !important; }');

Go to the sources tab in dev tools and right click in the left column, then add folder to workspace and use file explorer to select the folder that contains your css file. You will have to allow to make changes, once you do this you will see your folder in the sources tree(MAKE SURE YOU SELECT FILESYSTEM TAB UNDER SOURCES TAB), open your folder find the file and right click on the your css file and select map to network resource. Once you map the file you can open and see it in the workspace and from that file any change made will affect the page styles. So basically your styles will over ride the served styles.

Is this what you're after?: "How to Edit Source Files Directly in Chrome" http://www.sitepoint.com/edit-source-files-in-chrome/
From that article:
Step 1: Launch Developer Tools. Go to View -> Developer -> Developer Tools. Navigate to "Sources"
Step 2: Click the Filesystem tab, then click + Add folder to workspace. You’ll be prompted to locate your work folder and Chrome will ask you to confirm that you Allow access.
Step 3: Edit and Save Your Code and refresh the browser to see your changes

Related

How to get a summary of your CSS changes in Chrome dev tools?

Is there a way to get a list of the custom CSS changes you applied within the Chrome dev tools?
When you're playing with CSS in the Chrome dev tools to get your web page look right, it would come in handy to easily track the changes you made.
I know about workspaces, but the use case is an Angular 5 app where your CSS is bundled and possibly minified.
To clarify:
I have a page that is looking pretty far from what it should look like
I do 20 CSS fixes in dev tools until it looks good
now I want to get a (CSS) delta from the original page so I have a list of changes I should now implement in the real CSS styles.
You can see all changes via the Changes Drawer
In Dev Tools, you can locate the Changes Drawer via either:
A) Open Command Palette (Ctrl + Shift + P) and type "changes"
B) Open Drawer (Esc), click on the more options menu (triple dot), and select Changes
Further Reading
How to get a summary of your CSS changes in Chrome dev tools?
Export CSS changes from inspector (webkit, firebug, etc)
Updates
Dev Tools 98 added More precise changes to automatically pretty prints changes
Issue #1296143 opened User-Select: none in Changes drawer makes it very hard to utilize
Actually you could do exactly what you want:
Go to Sources > > Local Modifications
Going to the Sources tab, choosing your desired CSS file, and then right click and choose Local modifications will give you a diff style summary of your local changes.
Or - you could just save the changes directly to a local CSS file by mapping that local file so that chrome dev tools will automatically save any change that you made to this CSS file.
That depends on how you apply css fixes.
If you apply css code inline,you can't get a file with list of fixes you made.
If you made your changes in inspector-stylesheet you can find that file with all your fixes
Go to Source tab > from the left list open localhost > you can
see file called inspector-stylesheet.
Which will show all your fixes.
Another way to pick your css fixes from 'Elements' tab in dev tool you can easy copy edits you made and paste it in your css file of your project or you can edit source file itself from 'Source' tab in dev tool you have two things to do to keep what changes you made:
By pressing Ctrl + S or Cmd + S to save changes and automatically will save changes in your root css file in your project files.
You can copy and paste changes from dev tool to your css file in your code editor
Well, I learned something new 😯
How to monitor changes to inline styles in console
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
references: https://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/
const targetNode = document
// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
// Use traditional 'for loops' for IE 11
for(let mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('A child node has been added or removed.');
}
else if (mutation.type === 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
console.log({
mutation,
inline: mutation.target.style[0],
style: mutation.target.style[mutation.target.style[0]]
})
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
This does not solve the problem
but could be used as a starting point for a custom solution to the problem.
custom diffing of each element replacing old values with the latest values you could end up with a diff of all changes up to this point using your own maintained list.
This could be a pr to each of the browsers or created as a chrome extension. Goodluck, wanted to present a possible solution instead of saying it was impossible.
I know it's "another" subject, but you can try to launch it in some live checker extension in VS Code in order to follow everything...

How to reload single file in chrome developer tools

I'm working on a complicated site that has a lot of css files and js files that load on every page. I'm working on a single css using Chrome's developer tools. Once the css is mostly correct in developer tools, (Element tab, Styles side bar), the css is copied to a local css file and then uploaded to the web server. Since only a single css file has been modified it would be faster to reload a single css file instead of hard refreshing and reloading the entire site including images, js, and css, etc.
The site has an option to minify the css file and combine it with the other css files, creating one single very large css file. That option is turned off while in development mode. Adding a version number to the css file name isn't the trick I'm looking for.
Is it possible in Chrome Developer tools to click on a source file and refresh only that file?
This is a bit of a hack, but I think it'll work for your scenario.
When I initially load an example page, you can see three CSS requests:
I want to refresh the devsite-googler-buttons.css file, so I find it in my DOM Tree:
(Command+F on Mac or Control+F on Windows / Linux opens up that search panel at the bottom of the Elements panel... makes it easier to find stuff in a big DOM)
Right-click, select Edit as HTML, and then append a random query string to the end of the link:
And in the Network panel, you can see that the file was re-downloaded:
See also: Konrad's answer provides some handy code for automating this via a Snippet.
It might be handy, in your situation, to automate it a bit:
function reloadCSS() {
const links = document.getElementsByTagName('link');
Array.from(links)
.filter(link => link.rel.toLowerCase() === 'stylesheet' && link.href)
.forEach(link => {
const url = new URL(link.href, location.href);
url.searchParams.set('forceReload', Date.now());
link.href = url.href;
});
}
reloadCSS();
What this function does is it forces all CSS files to be reloaded by appending current time to their URLs.
You can modify it to target a specific file. You can run it from console, via DevTools 'snippets' functionality or make it into an extension.
If you don't mind refreshing the page, but don't want to re-download all resources, try the following.
Open the css file in a new tab. (You can right click css files from the Chrome developer tools and choose "open in new tab");
Hard-refresh this tab (ctrl/cmd + f5);
Soft-refresh the page (f5 or ctrl/cms + r).
According to me only Live editing is the only possible way what you are looking for I suppose. There is no way to refresh a single css file.

CSS will not apply to new page although file paths are no different

I am using the same style sheet for 2 pages (index.html & contact.html). All styling has been applied to index.html. Now I have copied and pasted the same code into contact.html, but have found that the new CSS styling I have tried to use will not apply to this page. The pathfile to the style.css sheet has not been changed. What I don't understand is why some of the styling is being applied from the other page but when trying to add new styling it does not?
Have you tried clearing your browser cache or going incognito/private browsing
Are you applying new styles using classes or ids? Id is unique, while classes are reusable. Also if you have inline styling it will override the stylesheet. Can you post your code as an example?
Well there can be a couple of reasons for this:
Make sure that your stylesheet is properly loading. I don't know if you are using in page styling or an external stylesheet but make sure that it actually exists there.
How can you do that? When you open the contact.html page in the browser, hit Ctrl + U if you are using windows or Command + U if you are using Mac. If it is an internal styling, you will be able to see the actual code there. If you are using an external stylesheet make sure that the <link> tag exists in the page. If it exists the right click on it and select Open file in a new tab. If you see can see the code in the next tab. It means that your styles are properly loading.
Make sure that your elements in the html page and stylesheet file have the same appropriate names. For example # of id's and . for classes.
If everything is okay then it can be a cache issue. Since browsers cache the static assets, you should consider refreshing the cache by Hard Reloading the page. How can you do that? It's simple, just hit Ctrl + Shift + R if you are using windows or Command + Shift + R if you are using Mac. If these keys don't work, just click and hold the reload button on the browser until it shows a dropdown. Then simply select Hard Reload.
In case it doesn't work, then send us a link to your webpage. I'm here to help you. Just let me now :-)

How to save CSS changes from Chrome without workspaces?

The current workflow for our designer is:
Opens web page and edit the CSS
Write up all the CSS changes in an issue
Is there a way for chrome to save the 'diff' of the CSS and export it without using workspaces?
As of Chrome 65, Local Overrides can help with this. Check your Chrome version at chrome://version. If you don't have 65 yet, you can use Chrome Canary.
Open Sources.
Click Local Overrides tab.
Click Select folder for overrides and choose a destination.
Make your changes in the Styles pane on Elements panel or Editor pane in Sources panel. Chrome saves the changed files to the specified location.
GOTCHAS!!!
Changes made in the DOM Tree on the Elements panel don't get saved.
Neither do changes made in the Styles pane when the source of the CSS rules is a <style> tag in HTML. At least in Chrome 65. There's rumors that this may get fixed in 66.
Not sure if that's what you want, but...
You can edit the page from inspector (ctrl+shift+I) and after done with all your changes, just click on the stylesheet link at your left and copy everything you need

How to enable real time CSS editing in chrome?

I have seem a lot of videos in which developers are changing CSS on the fly in chrome. I tried the same thing but chrome did not allow me to change the code. I can't write on the style sheet.
Is there any specific setting to do this? Kindly help.
EDIT: To edit the CSS, I right click on an element, select inspect element. It will open the console. I select the id of the element and go to style.css in Resources and try to change the CSS. It does not allow me to write there.
You are doing it wrong... the resources panel is not there for live edit, if you want to change the css associated with an HTML element, right click on that element and then in the right panel you will see the css styles associated with the selected element. You can edit that rules and you will see the changes in real time.
Maybe you can check some videos to learn some basics about the Chrome Developer Tools, and after that if you want to learn more, you can check this question:
Chrome Developer Tools: Best resource for learning advanced features?
Here is a great tool for Google Chrome called Stylebot.
In this you can change the style sheet and save your own styles to any website for your own custom website theme!
Here is the link for Stylebot
Check it out and to put the icing on the cake, it's free!
This should not be used to work on your own website projects since the CSS file saves local on your browser!
In Chrome, clicking on something like "all.css:1" in the Styles pane of the Elements tab of DevTools takes one to the Sources tab of DevTools. If you're looking at code on remote server, the CSS rules in this source view are not live-editable (unlike the live-editing Style Editor tab of Firefox*) unless you're:
viewing the "inspector-stylesheet" -- a temporary stylesheet containing new style rules you created with the "+" button in the Styles pane of the Elements tab. Clicking on a new rule's "inpector-stylesheet:1" link will take you to the editable source of the temporary rules you've created.
viewing a persistent local workspace. Setting this up takes a few extra steps, described here: "Set Up Persistence with DevTools Workspaces" .
Basically, you make a local folder on your machine where you can save local copies that you direct Chrome to use in in lieu of the version on the internet. See the instructions at that link. Note that, as it says there, "If you are mapping files from a remote server instead of a local server, when you refresh the page, Chrome reloads the page from the remote server. Your changes still persist to disk and are reapplied if you continue editing in Workspaces." (So just type a space character into the source local CSS file to see your alterations applied again, if you've refreshed or navigated to a different page that uses the same stylesheet.)
* In Firefox, if you right-click on an element on a remote webpage, select Inspect Element, then in the Rules pane of the Inspector tab, click on a link on the right like "all.css:1", you are taken to a "Style Editor" tab where you can immediately live-edit, in contrast to Chrome's requirement of making you map to a local file. This may cause some people some confusion, if they expect the same behavior from Chrome's DevTools.
Another Chrome extension that is similar to Stylebot is Code Cola. It has an inspector that allows selecting elements, and a visual editor which does not require typing the CSS by hand. To see the generated CSS code click the curly brackets icon in the toolbar.

Resources