Search code examples
cssstylesheet

Conquering CSS, algorithmically


Before delving into my question, I should first provide a synopsis of what angle I'm coming from: for most of my web development work (up until about a year ago), I have focused almost entirely on back-end development. Hence, much of my recent months have been spent coming up to speed on JavaScript, AJAX tools, JS libraries, DOM Manipulation, and of course: Cascading Style Sheets. I have found a way to adapt and leverage my mode of thinking to just about all of these aspects of web-development and do some truly neat things but CSS continues to be elusive to me. Just about every web resource I've encountered that explains how to use CSS, describes this technology in a very piece-meal fashion. So far I see nothing more than and endless list of example layouts and styles that make them happen. And of course, to make matters worse: there's often multiple ways to achieve the same end, and a myriad of fragmented "gotchas" to deal with browser inconsistencies.

To me: CSS is not a fully-functional programming language (i.e. it is not Turing complete). Hence, learning CSS is like trying to hack a complex XML file without having a clear idea how the software consuming said file will interpret it. What I am looking for is an algorithmic description of exactly how CSS is interpreted by each of the major browsers (IE, Chrome and FireFox). To me, this would be far more preferable than the brute-force approach I've been forced to use so far.


Solution

  • CSS is indeed a different beast. As you suggested, it is not Turing complete. Furthermore, understanding a Turing complete language will not help you very much with understanding CSS. A CSS rule that you write may or may not be applied by the browser depending on many factors:

    • "Weight"
    • Location
    • Importance
    • Scope
    • Inheritance

    You almost have to get into the browser's head to write CSS :). But, these resources should help you:

    Straight from the source: http://www.w3.org/TR/CSS2/cascade.html

    Article: http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/


    Edit

    If you'd like to check out some of the actual code that performs these calculations (example being Firefox), then look through these files at the link below. Included, also, are the default CSS rule sets that Firefox applies automatically to every page.