Count number of selectors in a css file
The following snippet can be run in the Firebug console in Firefox to count the total number of CSS selectors (not just CSS rules) and check whether it reaches the limit of 4095 selectors per stylesheet:
var
styleSheets = document.styleSheets,
totalStyleSheets = styleSheets.length;
for (var j = 0; j < totalStyleSheets; j++){
var
styleSheet = styleSheets[j],
rules = styleSheet.cssRules,
totalRulesInStylesheet = rules.length,
totalSelectorsInStylesheet = 0;
for (var i = 0; i < totalRulesInStylesheet; i++) {
if (rules[i].selectorText){
totalSelectorsInStylesheet += rules[i].selectorText.split(',').length;
}
}
console.log("Stylesheet: "+styleSheet.href);
console.log("Total rules: "+totalRulesInStylesheet);
console.log("Total selectors: "+totalSelectorsInStylesheet);
}
How are media queries counted in IE's CSS selectors limit?
It appears that media queries are not included in the selector limit. All rules within all media queries are counted though.
I wrote a test that performs a binary search to find the turning point where the last selector is ignored. It is available at https://robwu.nl/s/css-selector-limit-test.html. The binary search runs over the range 0 - 4200 and reports how often the input selector fits until the last selector is not applied any more. If the result is greater than 4096, the test case reports "infinity".
Results:
Turning point at 4095 for: #DUMMY{color:red;}
Turning point at 4095 for: @media screen(min-width:9px) { #DUMMY {color:red;} }
Turning point at 2047 for: @media screen(min-width:9px) { #DUMMY, #DUMMY {color:red;} }
Turning point at 1023 for: @media screen(min-width:9px) { #DUMMY {color:red;} #DUMMY, #DUMMY, #DUMMY {color:red;} }
Turning point at 1364 for: @media screen(min-width:9px) { #DUMMY {color:red;} } @media screen(max-width:9px) {#DUMMY, #DUMMY {color:red}}
Turning point at 1364 for: @media screen(min-width:9px) { #DUMMY {color:red;} } @media screen(max-width:9px) {#DUMMY {color:red;}} @media screen(max-width:9px){ #DUMMY {color:red;}}
Turning point at infinity for: @media screen (min-width:9px) { }
Turning point at infinity for: @media screen (min-width:9px) { } @media screen (min-width:9px) { } @media screen (min-width:9px) { }
Turning point at infinity for: @font-face { font-family: "blablablablabla"; }
The last three tests show that media queries (and other at-rules such as @font-face
) are not counted in the selector limit.
I have seen many "css rule" counter scripts here on Stack Oveflow (e.g. https://stackoverflow.com/a/20496041 and https://stackoverflow.com/a/12313690), but all of them are wrong, unfortunately. A media query appears as one entry in the cssRules/rules list. The right way to count the number of selectors in a stylesheet is to recursively process the style sheet to deal with (nested) @media
at-rules.
How can I count the number of elements that match my CSS selector?
As far as I am aware you can't do this using CSS selectors, but there is a command in Selenium for counting by XPath. The following command will verify there are two disabled buttons:
verifyXpathCount | //td[contains(@class, 'x-hide-offsets')]//button | 2
In Selenium RC (Java) this would look more like
assertEquals(selenium.getXpathCount("//td[contains(@class, 'x-hide-offsets')]//button"), 2);
Count css selectors on a website
Try this:
Firebug CSS Usage
Way of Determining How Many Style Rules I have
Through the command-line: You could pass the html file to grep, and do a word count on the occurences of css.
grep css index.html | wc -l
Can CSS detect the number of children an element has?
Clarification:
Because of a previous phrasing in the original question, a few SO citizens have raised concerns that this answer could be misleading. Note that, in CSS3, styles cannot be applied to a parent node based on the number of children it has. However, styles can be applied to the children nodes based on the number of siblings they have.
Original answer:
Incredibly, this is now possible purely in CSS3.
/* one item */
li:first-child:nth-last-child(1) {
/* -or- li:only-child { */
width: 100%;
}
/* two items */
li:first-child:nth-last-child(2),
li:first-child:nth-last-child(2) ~ li {
width: 50%;
}
/* three items */
li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
width: 33.3333%;
}
/* four items */
li:first-child:nth-last-child(4),
li:first-child:nth-last-child(4) ~ li {
width: 25%;
}
The trick is to select the first child when it's also the nth-from-the-last child. This effectively selects based on the number of siblings.
Credit for this technique goes to André Luís (discovered) & Lea Verou (refined).
Don't you just love CSS3? /p>
CodePen Example:
- https://codepen.io/mattlubner-the-decoder/pen/ExaQZQR
Sources:
- http://andr3.net/blog/post/142 (André Luís)
- http://lea.verou.me/2011/01/styling-children-based-on-their-number-with-css3/ (Lea Verou)
CSS get total number of elements
Unfortunately, there is no way in both CSS or LESS to do that. You can go with a JavaScript solution, which is fairly simple to implement.
Rough idea:
var allChildren = document.querySelectorAll('#myContainer > *');
var count = allChildren.length;
allChildren[count-1].style.width = 'calc(100% - '+ count * 50 +'px)';
Your specific problem (always better to post a specific problem!) can be solved easily with a HTML table:
HTML:
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>last</td>
</tr>
</table>
CSS:
table {
width:300px;
border:1px solid red;
}
td {
width:50px;
border: 1px solid blue;
}
td:last-child {
width:auto;
}
DEMO: http://jsbin.com/eTeBudiR/1/edit
If the data you want to display is not tabular in nature and you just want the layout to look like that, you can use CSS (display:table
, display:table-cell
) to achieve the same result.
HTML:
<div id="myContainer">
<div>1</div>
<div>2</div>
<div>3</div>
<div>last</div>
</div>
CSS:
#myContainer {
display:table;
width:300px;
border:1px solid red;
}
#myContainer > div {
display:table-cell;
border:1px solid blue;
width:50px;
}
#myContainer > div:last-child {
width:auto;
}
DEMO: http://jsbin.com/eTeBudiR/2/edit
Checking number of times CSS classes called.
Just for fun, I wrote one.
try it
First we need to find our style sheet. In an actual script, this would be written better, but this works on jsFiddle.
var styles = document.head.getElementsByTagName('style');
var css = styles[styles.length - 1].innerHTML;
Then remove comments, and the bodies of each selector (i.e. the stuff between the brackets). This is done because there could be a .com
in a background-image property, or any number of other problems. We assume there isn't a }
in a literal string, so that would cause problems.
var clean = css.replace(/\/\*.*?\*\//g, '').replace(/\{[^}]*\}/g, ',');
We can find classes with regular expressions, and then count how many of them occur.
var re_class = /\.(\w+)/g;
var cssClasses = {}, match, c;
while (match = re_class.exec(clean)) {
c = match[1];
cssClasses[c] = cssClasses[c] + 1 || 1;
}
I used jsprint for displaying our findings. This shows how many times each class is mentioned in our CSS.
jsprint("css classes used", cssClasses);
Thanks to Google and this answer we can find all elements in the body, and loop through them. By default, we assume no classes were used in our HTML, and all classes used were defined.
var elements = document.body.getElementsByTagName("*");
var neverUsed = Object.keys(cssClasses);
var neverDefined = [];
var htmlClasses = {};
We get each elements class, and split it on the spaces.
for (var i=0; i<elements.length; i++) {
var e = elements[i];
var classes = (e.className || "").split(" ");
This is a three dimensional loop, but it works nicely.
for (var j=0; j<classes.length; j++) {
for (var k=0; k<neverUsed.length; k++) {
We thought classes[j]
was never used, but we found a use of it. Remove it from the array.
if (neverUsed[k] === classes[j]) {
neverUsed.splice(k, 1);
}
}
It looks like we found a class that doesn't appear in our CSS. We just need to make sure it's not an empty string, and then push it onto our array.
if (classes[j].length && cssClasses[classes[j]] == null) {
neverDefined.push(classes[j]);
}
Also count the number of times each class is used in HTML.
if (classes[j].length) {
htmlClasses[classes[j]] = htmlClasses[classes[j]] + 1 || 1;
}
}
}
Then display our results.
jsprint("html class usage", htmlClasses);
jsprint("never used in HTML", neverUsed);
jsprint("never defined in CSS", neverDefined);
How can I use javascript to count the number of items on screen with a certain class?
document.querySelectorAll('#main-div .specific-class').length;
this will look for and find all DOM elements with class specific-class and under(doesn't matter if it is directly under or not) DOM element with id main-div.
If you want to find all elements with specific multiple classes and get length of elements, you should remove space between classes in querySelectorAll.
So if you have a HTML tag with classes
class="toggle btn btn-default off"
you should do
let elements = document.querySelectorAll('toggle.btn.btn-default.off').length;
Related Topics
Svg + CSS3 Animation Not Working with Link Markup
404 Errors on Bundled Jquery CSS, VS2012 Publishing to Azure
Change the Default Responsive Navbar Breakpoint
Why Doesn't My Child Element Inherit Color from Its Parent When Parent Has More Specific Selector
Sidemenu Background-Color in Ionic-V4
Ie11 Making Background Image Text Blurry
Difference Between Blank and Empty Pseudo-Classes
How to Identify and Eliminate Unused CSS Styles from My Bloated Stylesheet
Display:Block Not Working in Chrome or Safari
(Sass) How to Exclude My Imported Files to Compile to CSS Files
How to Set the 'Left' Property of My Div Using CSS3 Calc
How to Use Srcset and Sizes for Responsive Images
Do Ie Browsers (IE6, 7, 8) Support @Font-Face
Eliminate External Render-Blocking
Are There Any CSS Standards That I Should Follow While Writing My First Stylesheet