Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How long can a CSS selector be?

How long can a CSS selector be?

I'm not too interested in what the 'spec' says, but rather, what browsers can actually handle. So far, I'm only aware of one browser which chokes on (very) long selectors; chrome.

Edit: Example where Chrome does not apply CSS rule to some countries, e.g. the US, Turkey, Syria and the UK, and the CSS. There are 7 selectors, and at least #5 is too long for some browsers.

like image 409
leo Avatar asked Dec 29 '13 19:12

leo


1 Answers

ScottS concluded Chrome handles 1366 selectors. Why 1366?

1366 * 3 = 4098

Why 3? There are 3 components in this selector: .y1366 .c1 > *. 4098 is the limit of total number of selector parts. Proof here (I added > * to the first selector only and it marked 4095 elements instead of 4096).

My tests

A group of 4096 selectors will have the remaining ones completely ignored. Example:

.z .y1, .z .y2, .z .y3,..., .z .y3{background-color:red}

Live Example

In the example each selector has 2 components:

.y1 > *
Component 1: .y1
Component 2: *

Every selector placed after the 2048th is ignored. Why 2048? Because each selector has 2 components and the limit is 4096. Not convinced?

Next example

In the example above each selector has one component:

.y1, .y2, .y3 ...

Only the first 4096 selectors are working. Chrome doesn't have a limit, so all of the selectors should work. Yet after a certain point, remaining selectors are completely ignored. This bug existed for at least 2 years. IE9 and below have a limit of 4095 selectors.

Bug 2

A large group of selectors, one of them having two components .bdy .y1 will, after 4096 combined components cause the element with class bdy to be affected.

Example

.bdy .y1, .y2, .y3, ... .y4097{background-color:red}

The CSS selector group above causes an element by class name bdy to have background-color:red applied. The condition is to have 4096 selectors after one selector with two components.

Live example

In the example above the body is applied with red color due to a 4096 selector (after one which targets a child of an element with class name bdy which has class name y1). The bug will cause the parent to be affected.

In .bdy .y1 the element .y1 (under parent .bdy) is targeted, yet an element bdy is also affected. If you move the two component selectors 10 places forward you can create 10 more selectors until this bug manifests. That implies the bug occurs when total number of component selectors reaches 4096.

SOLUTION

They are not going to fix it. This problem will happen only if all selectors are on one line. So just do:

.c1 .y1,
.c1 .y2,
.c1 .y3...

instead of:

.c1 .y1, .c1 .y2, .c1 .y3...
like image 96
Milos Avatar answered Oct 07 '22 09:10

Milos