Find All CSS Styles Used on Website

Extracting only the css used in a specific page

I've used Dust-Me Selectors before, which is a Firefox plugin. It's very easy to use and versatile as it maintains a combined list across a number of pages of which CSS values are used.

The downside is that I wasn't able to automate it to spider an entire site, so I ended up using it just on key pages/templates of my site. It is very useful nonetheless.

http://www.sitepoint.com/dustmeselectors/

https://addons.mozilla.org/en-US/firefox/addon/dust-me-selectors/

Contrary to the comment above Dust-Me Selectors 2.2 is compatible with Firefox 3.6 (I've just installed it).

Is there a way to check which CSS styles are being used or not used on a web page?

Install the CSS Usage add-on for Firebug and run it on that page. It will tell you which styles are being used and not used by that page.

Find out where the CSS codes are used in the web page after Pick out them via Chrome DevTools?

Hei, instead of going to the source options, go in the Elements tab and look over the rule you are searching for, press on it and on the right you can see which file applies that style, and at which row. Like the screenshot below (just an example)
Example

EDIT

2 CSS files use the same class name for the same CSS rule, how to find such a case?

Well, there are cases where multiple CSS files could apply style at the same class element. This divides into 2 categories:

  1. The one that applies different styles to the same class
  2. The one that applies the same styles to the same class

In the first case, there are no issues, and both styles will be applied. And to track those styling rules, you'd need to check both files.

In the second case, the style will be applied by the last rule, so the last read by the system (example below)
You can see how it works

Also, on the second posted screenshot, you can see that the element that has "no applied style" simply does not exist, and is not a real element but a string
noscript
You can see in this screenshot that the image element is written between double quotes and does not represent a real HTML element. so no styling will be applied

How can I grab all css styles of an element?

UPDATE: As @tank answers below, Chrome version 77 added "Copy Styles" when you right-click on an element in the devtools inspector.


Using Javascript worked best for me. Here's how I did it:

  1. Open Chrome DevTools console.
  2. Paste this dumpCSSText function from this stack overflow answer into the console, and hit Enter:

    function dumpCSSText(element){
    var s = '';
    var o = getComputedStyle(element);
    for(var i = 0; i < o.length; i++){
    s+=o[i] + ':' + o.getPropertyValue(o[i])+';';
    }
    return s;
    }
  3. When using Chrome, you can inspect an element and access it in the console with the $0 variable. Chrome also has a copy command, so use this command to copy ALL the css of the inspected element:

    copy(dumpCSSText($0));
  4. Paste your CSS wherever you like! /p>

Find out what CSS styles are being used on a given page

I think this website does what you want: CSS Trashman. It takes a little while to run, but it works. It reduced my personal site's CSS from 3.31 KB to 402 Bytes.

If you would rather use a command-line tool, CSS Rationator powers CSS Trashman.

Is there a way to find all the global styles that apply to a web page?

The only option for evaluating the current page's CSS styles is to use document.styleSheets. It will return a list of CSSStyleSheets.

You will want to focus on document.styleSheets[n].cssRules, where n equals which stylesheet you want to evaluate. That will give you a list of all the styles applied by that stylesheet. Each stylesheet will have a cssText and a selectorText property.

If you just want to loop through to find which styles are 'non-namespaced' you should probably just use the selectorText properties.

Here is some more information on MDN about document.styleSheets.

Here is an example (press 'Run code snippet' to see results):

var selectors = [];
var sheets = Array.from(document.styleSheets);
sheets.forEach(function(sheet) { // Only Stylesheets from a same-origin domain expose `cssRules` for security reasons try { var rules = Array.from(sheet.cssRules); rules.forEach(function(rule) { selectors.push(rule.selectorText); }); } catch (e) { // Do something with external stylesheets if you want }});
console.log(selectors);
<!DOCTYPE html><html>
<head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Stylesheets</title> <style> .hello-world { background: url(none.gif); } </style> <!-- Won't work as it is not a same-original stylesheet --> <link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.2/normalize.min.css" rel="stylesheet" type="text/css" /></head>
<body> <style> .foo { background: url(none.gif) } .bar { background: url(none.gif); } </style></body>
</html>

Is there a way to list all available css classes for a web page?

A bit late but ...

  for (let link of document.querySelectorAll("link, style")) {
try {
if (!link.sheet) {
console.warn("Warning:", "Property 'sheet' is not set on element", link)
} else
for (let rule of link.sheet.rules) {
console.log(rule.selectorText)
};
} catch (e) {
console.warn("Warning:", e.message, ". Try set crossorigin='anonymous' on element", link)
}
};

or in the Chrome DevTool window (F12), find the "Elements", then "Styles", tab. On the right side of the "filter" text-box there is a ".cls" option. Click it and an "add new class" input should appear. Focus that input and hit Ctrl + Space. A pick list of all class styles in the current opened document should appear.

It looks something like this:
Sample Image

Getting all css used in html file

For inline stylesheets, you can get the content out of the normal DOM like with any other element:

document.getElementsByTagName('style')[0].firstChild.data

For external, linked stylesheets it's more problematic. In modern browsers, you can get the text of every rule (including inline, linked and @imported stylesheets) from the document.styleSheets[].cssRules[].cssText property.

Unfortunately IE does not implement this DOM Level 2 Style/CSS standard, instead using its own subtly different version of the StyleSheet and CSSRule interfaces. So you need some sniff-and-branch code to recreate rules in IE, and the text might not be exactly the same as the original. (In particular, IE will ALL-CAPS your property names and lose whitespace.)

var css= [];

for (var sheeti= 0; sheeti<document.styleSheets.length; sheeti++) {
var sheet= document.styleSheets[sheeti];
var rules= ('cssRules' in sheet)? sheet.cssRules : sheet.rules;
for (var rulei= 0; rulei<rules.length; rulei++) {
var rule= rules[rulei];
if ('cssText' in rule)
css.push(rule.cssText);
else
css.push(rule.selectorText+' {\n'+rule.style.cssText+'\n}\n');
}
}

return css.join('\n');

Find all CSS styles used on website

For firefox there is an add-in called dust-me-selectors. If you provide a sitemap, it will find all unused css styles.

How can I extract only the used CSS on a given web page and have that combined into a separate style sheet?

(deleted my comment to RwwL answer to make it a thorough answer)

UnCSS, whether node.js or as a grunt or gulp task, is able to list used CSS rules by an array of pages in an array of Media Queries.

uncss: https://github.com/giakki/uncss

grunt-uncss: https://github.com/addyosmani/grunt-uncss

gulp-uncss: https://github.com/ben-eb/gulp-uncss

Multipage:

You can pass files as an argument to any of the 3 plugins, like:

var files   = ['my', 'array', 'of', 'HTML', 'files'],
options = { /* (…) */ };

uncss(files, options, function (error, output) {
console.log(output);
});

Avoid:

urls (Array):

array of URLs to load with Phantom (on top of the files already passed if any).

NOTE: this feature is deprecated, you can pass URLs directly as arguments.

 

Media Queries and responsive are taken into account:

media (Array):

By default UnCSS processes only stylesheets with media query "all", "screen", and those without one. Specify here which others to include.

You can add stylesheets, ignore some of them, add inline CSS and many other options like htmlroot

 

Remaining problems:

1/ Conditional classes if you use them for IE9-. They obviously won't be matched in a WebKit PhantomJS environment!

HTML:
<!--[if IE 9]><html class="ie9 lte-ie9" lang="en"><![endif]--> <!-- teh conditional comment/class -->

CSS:
.ie9 .some-class { property: value; ] /* Only matched in IE9, not WebKit PhantomJS */

Should they be added by hand or script to the html element in testing environment? (how it renders is of no importance)

Is there an option in uncss?

As long as you don't style with :not(.ie9) (weird), it should be fine.

EDIT: you can use the ignore option with a pattern to force uncss to "provide a list of selectors that should not be removed by UnCSS". Won't be tested though.

2/ Scripts that will detect resolution (viewport width) and adapt content to it by removing/adding it or adding a class on a container. They will execute in PhantomJS in desktop resolution I guess and thus won't do their job so you'll need to modify calls to PhantomJS or something like that... Or dig into options or GitHub issues of the 3 projects (I didn't)

Other tools I heard of, not tested or barely or couldn't test, no idea about the MQ part:

  • in grunt-uncss readme, the Coverage part
  • ucss from Opera (there's already an ansswer here, couldn't make it work)
  • Helium
  • CSSESS
  • mincss

Addy Osmani has countless presentations of 100+ slides presenting awesome tools like this one: https://speakerdeck.com/addyosmani/automating-front-end-workflow (you'll regret even more that days are made only of 24 hours and not 48 err wait 72 ^^)



Related Topics



Leave a reply



Submit