Pandora’s Box

This post is part of my personal notes in a larger effort in thinking about benefits now that are currently specified in Shadow DOM, but contentious and held up in committee.  We’ll work it out in standards, I’m sure – but given the number of things Shadow DOM was addressing, it may still be several years until we have solutions widely implemented and deployed that solve all of them.  This has me doing a lot of thought exercises about what can be done in the meantime.  This post reflects one such exercise:  Specifically, what would it mean to solve just the styling end of this on its own. Warning, it may be mildly crazy so the title is perhaps doubly relevant. It was originally posted on

B3t0l4FIAAAPxkUThe Pandora Box

CSS works really well if you can follow good patterns and have nice rich markup. It lets you define broad rules and inherit and override selectively, and if used well it cleanly decouples a separation of concerns — it’s pretty elegant actually.

On the other hand, in the real world, things are often not that simple: Until pretty recently, HTML wasn’t especially expressive natively, so we worked around it. – many times on our own by adding classes like “article”.  But, there wasn’t a standard.  Likewise, our ideas about the patterns we should follow or best practices continues to change as we gain new powers or spend more time with the technology. Of course, there are a vast number of cases where you’ll just go and upgrade your philosophy and be the better for it, but there are a number of times when this just isn’t an option. I recently described this in a recent post as the “friendly fire” problem – when you have numerous teams operating on different time schedules and budgets across many code bases that attempt to mash together into various forms. This is sometimes referred to in standards circles, less colorfully, as “the composition problem”.

When it comes to these sorts of cases, quality and philosophy are inevitably mixed and not entirely in the control of any one team. In these sorts of cases, CSS selectors are kind of like live hand-grenades, it’s just way too easy to do damage you didn’t intend to do because it requires a level of coordination of approach which is, for business reasons, highly impractical. And so you try really hard to analyze the problem, get the right select/cascade/descend/inherit/specificity, pull the pin, lob it into the pages and… hope. Frequently, all hell breaks loose. The more you mix it up, the harder it gets to reason about and the more our stylesheets explode in complexity. You’ve opened the proverbial Pandora’s Box.

You can see this in play in some simple examples. If the page begins with assumptions and a philosophy of it’s own and then injects markup created by another team with a differing philosophy without adopting their CSS as well, the results are frequently bad. Here’s one such (overly simplified) example in which you’ll notice that the taxonomy of classes overlap and the result is that the inner context has bits that not only themselves become unreadable but obscure the page’s (already pretty bad) content. If the page does include the other team’s CSS it can easily get worse, as seen in this example in which you’ll notice both ends have harmed each other to the point of complete uselessness.

At a minimum, one proposal that seems to keep coming up in various forms (most recently Shadow DOM) is to provide a way, in cases like these, for authors to isolate the styling of various pieces so that the default thing is to do no harm in either direction, thereby just simplifying the problem.  But, for now, the platform doesn’t provide you an easy way to do that…. but it does provide a way to fake it, and that might be useful.  In the very least it can help us to figure out exactly what it is we need: Without data, standardization is hard and often a bad idea.  So much discussion is about what we think developers will find intuitive or confusing.  A better way is to know what developers understand or don’t.  So let’s see if we can try to tamp down a cow path.

Thinking about how CSS works

initial-values: All elements have all of the CSS properties from the get-go, all CSS properties have a default, or initial value which is specified in the specification.

A screenshot of the CSS2.1 spec showing the initial value for the display property was 'inline' at the time (it's grown more complicated but the net effect is the same)

The initial value for each property is provided in the spec.

For simplicity, you can sort of imagine that without anything more, all elements begin their life with properties that would look to most of us like a <span>. I’m guessing this is news to a lot of long time users of CSS because we pretty much never experience this world because browsers (“user-agents” in standards speak) come with a stylesheet of their own…

user-agent stylesheets: All browsers come with a default, or “user-agent” stylesheet. This is the thing that tells them how to display an element in the first place, and it does so with the same kinds of CSS rules that you and I write every day. Without it, you’d be able to see the contents of those <style> and <script> tags, your <h1> would look just like any other piece of text, and so on.  You can see one such example in Firefox’s stylesheet. So: initial values + user-agent sheet yields what you’d get if you started editing an HTML document, before you started adding your own CSS (“author CSS” is what we generally call that stuff).

specificity: The CSS runtime is a rules engine – all of the rules are loaded in order and maintain a stable sort based-on a concept called “specificity”. That is, each rule gets a weighted “score” according to the selector it is based on. A “*” in the selector is worth 0 “points”, a tag is worth 1, a class is worth an order of magnitude more (it’s not specifically 10 based, but for illustration you can assume 10 points), an id is worth 100. So the reason author CSS trumps the user-agent stylesheets is simply the user-agent stylesheet is very low specificity and it came first – authors will always be either more specific or have come later.

And this is where things get sticky…

In situations like the ones described above, if you’ve got a independently developed components working on differing models or timeline, no side can really know what they’re likely to inherit, what to override or how to do it (because specificity). Reasoning about this is really hard – many big companies or products have stylesheets that are many thousands of rules, and frequently not just one that must work with a vast array of content of varying age, quality and philosophy.

Keep a lid on it…

At some level, we can imagine that we’d like to identify a container as a special thing, let’s call it a “pandora-box” – the kind of integration point we’re talking about- and have it do just what the browser does with a fresh page by default for that container.  In this model, we’d like to say “Give me a clean slate (reset the defaults and provide a user-agent-like sheet for this sort of container).  Let my rules automatically trump the page within this container, by default, just like you trump the user agent… Likewise, keep my rules inside this Pandora’s Box by default”.  Essentially, we’d like a new specificity context.

If you're thinking this seems a little like a Rube Goldberg machine, it's  not quite so out there - but, welcome to the Web and why we need the sorts of primitives explained in the Extensible Web Manifesto

If you’re thinking this seems a little like a Rube Goldberg machine, it’s not quite so out there – but, welcome to the Web and why we need the sorts of primitives explained in the Extensible Web Manifesto

Well, to some extent, we can kind of do this with a not too hard specificity strategy that removes the most of the hard-core coordination concerns: We can use CSS’s own specificity rules to create an incredibly specific set of default rules, and use that as our box’s equivalent of a ‘default stylesheet’  – basically resetting things.  And that should work pretty much everywhere today.

The :not() pseudo-class counts the simple selector inside for its specificity. So, if we created an attribute called, for example, pandora-box and then picked an id which would be incredibly unlikely to exist in the wild (say #-_- because it’s not just unique but short and shows my ‘no comment’ face), then, it would – using CSS’s own theory, provide a clean slate within the box. And, importantly, this would work everywhere today (because we would wind up with a single “pandora-box stylesheet” with rules like [pandora-box] h1:not(#-_-):not(#-_-):not(#-_-) { ... } which has a specificity of 3 ids, 1 attribute and 1 tag (311 in base-10 – again CSS isn’t base-10 but it’s helpful for visualization to assign a meaningful number), enough to trump virtually any sane stylesheet’s most ambitious selector).

Given this, all you need is a way to shove the component’s rules into the box and shut the lid and you have a pretty easy coordination strategy.  You’ve basically created a new “context”.

Essentially, this is the same pattern and model as the page has with user-agent sheets, at least mentally (initial values are still initial values and they could have been modified, so we’ll have to reset those in our pandora sheet as well).

In simple terms, A pandora box has two sets of rules – the default and the author provided that parallel the user-agent (default) and author.  The automatic ordering of specificity in naturally such that the automatic pattern for resolution is: User-agent default stylesheet, then normal author stylesheets, then pandora-box default stylesheet then pandora-box author stylesheets.

If you can follow this model, you should be able to work cooperatively without the risks and figure out how well that approach works.  Of course, no one wants to write a ton of :nots but we have preprocessors which can help and, maybe we can write something helpful for basic use that doesn’t even require that.

So, here’s a quick test pandora-box.js which does just that. Including it will inject a “pandora-box stylesheet” (just once) and give you a method CSS._specifyContainer(containerElement) which will shove any <style> tags within it to a more specific ruleset (adding the pandora/specificity boosts). The file has a couple of other methods too but they all are just alternate forms of this for a trying out a few ways I’m slicing up the problem – one that allows me to hoist a string of arbitrary cssText, another that I’m playing with in a larger custom element pattern.  You can see this in use in this example, it is identical to the previous one in terms of HTML and CSS.

Interestingly, CSS has an all property for unwinding the cascaded values simply.  Unfortunately, it doesn’t have an equivalent to ‘default’ things back to the fresh page state (the one that includes the user-agent sheet), only to nuke all styles back to their initial values, which, in my mind, leaves you in a pretty bad spot.  However, if it did, our pandora sheet would be essentially a single declaration: [pandora-box]:not(-_-):not(-_-):not(-_-) * { all: user-agent; }. Luckily, that’s under discussion by the CSSWG as you read this.

One question that is semi-unresolved is just what should that pandora sheet actually contain. How much is really necessary and, should it perhaps include common reset rules. I’ve taken what I think is a pretty sane stab at it, but all of this is easily tweaked for experimentation, so feel free to fork or make suggestions. The real goal of this exercise is to allow for experimentation and feedback from real authors, expand the conversation and highlight just how badly we need to solve some of these problems.

What about performance?!

The injection of rules happens just once, I don’t think that is likely a big perf problem. Besides the pandora-box stylesheet, you have exactly the same number of rules (your components rules are replaced, not duplicated) and because it’s easier to reason about you should be able to have generally less crazy sheets. At least, that’s what I hope. Only time and use will really tell. If you’re worried about the complexity of the selectors slowing things down dramatically, I doubt that’s much of a problem either – browsers use a bloom filter and such cleverness that evaluating the pandora sheet should have not much effect and the triple :not’s are placed on the subject element of the selector, so there shouldn’t be much computational difference between something no one would have trouble writing like [pandora-box] .foo and the rule it rewrites to [pandora-box] .foo:not(-_-):not(-_-):not(-_-), it never walks anywhere.

What about theming?!

Pandora shut the box vowing never to open it again. But when a tiny voice begged to be let out, she opened it one las time. As well she did, for the creature left was the one we call Hope

Pandora’s box art from by Marta Dahlig

This seems to be one of the great debates – clearly there *are* certain kinds of advice you want an outer page to provide to the stuff in these various pandora boxes – things like “the background of this calendar component should be blue”.

In case it’s not obvious, the basic principle at play here is that just like selectors are managed with orders of magnitude, this technique employs those to create order of magnitude ‘contexts’. So, if you created a new context with specificity, you can simply trump it, just like anything else.  That is to say that if you really really wanted to pierce through from the outside, you’d just have to make those rules _really_ specific (or just place them after with the same specificity).  The key is that it has the right default behaviors – the calendar defines what it is to be a calendar and the page has to specifically say “except in these ways”.  If you look back at pandora-box.js, you can use the same API to allow the page to add rules, or there is a simple pattern which was also demonstrated in the last codepen example: If the thing you contain has an ID, it will see if there is a matching style tag in your page with a special type <style type="text/theme-{id}">, where {id} is the id of the container. If it finds one, all of those rules will be placed after the component’s rules and will therefore theme in the same way an author customizes native elements.

So, be part of the conversation. Let’s figure out what works and doesn’t in solving the friendly fire problem in CSS. Would the ability to put a lid back on Pandora’s Box be helpful?