CSS Selectors

Quick talk on writing efficient CSS Selectors, covering;

  • Browser interpretation
  • Pre-processors
  • Selectors order of Efficiency
  • The DOM impact
  • Sources & Help

Browser Interpretation

By process of elimination the browser parses CSS rules to locate targets.

Consider:
form#unique > div {}

Question: for the above rule what would the first set of elements consist of?

Answer: All of the div elements in the entire DOM.

Browsers read your CSS selectors from RIGHT to LEFT

Pre-processors

Stylus, SASS, LESS, etc. are great productivity tools.

Consider LESS:
body{ table { &.class1 { } &.class2 { } } }
Compiled:
body table.class1{ } body table.class2{ }

Pre-processors can offer great structure, and maintainability. But what is wrong here in terms of performance?

  • Overly complex rules for the browser interpretation
  • Multiple levels of computation due to the encapsulated classes
  • Has simple vanilla CSS implementation

Order of Efficiency

Note: Selectors efficiency may not suite all use cases.

  • ID - example: #unique
  • Class - example: .reusable
  • Tags - example: tr
  • Adjacent sibling - example: tr + th
  • Child - example: div > p
  • Descendant - example: div a
  • Attribute - example: [type="email"]
  • Pseudo - example: :focus

Please don't go crazy and style ID's

The DOM impact

Knowing that CSS selectors are read from RIGHT to LEFT we now consider;

  • The entire DOM is a factor.
  • Complex rules add levels of computation.
  • Unused CSS styles are evaluated.
  • Anything to the left of an ID is irrelevant.
  • Try to remove anything on the left of a good performing selector.
  • Clever rules targetting something specific may not have been very smart afterall.
  • Yes, jQuery is also a consideration.

Sources

CSS SELECTORS

By Chris Langton

CSS SELECTORS

  • 1,028