Revision of Twine: apply CSS to passages with specific tags from Sun, 02/10/2013 - 21:38

You can write CSS that applies only to passages that have been given specific tags in Twine!

If you're using this 1.3.6 alpha you can use this syntax on passage div elements out-of-the-box, but to use it to format body elements requires including this Javascript code, inside a disconnected passage that has "script" as its only tag:*

Passage.prototype.render2 = Passage.prototype.render; Passage.prototype.render = function () { var b = this.render2(); document.body.setAttribute("data-tags", this.tags.join(" ")); return b; };

If you're using a standard, earlier version of Twine you'll need to include this Javascript code, inside a disconnected passage that has "script" as its only tag:

Passage.prototype.render2 = Passage.prototype.render; Passage.prototype.render = function () { var b = this.render2(); var t = this.tags.join(" "); b.setAttribute("data-tags",t); document.body.setAttribute("data-tags", t); return b; }; if(state) { var tgs = state.history[0].passage.tags.join(" "); var fc = $('passages').firstChild; fc.setAttribute("data-tags",tgs); }

...and if you're using Sugarcane, add this code after that to make it work with the Start passage and bookmarked passages:

if(state) { var it = setInterval(function(){ var fd = $('passages').firstChild; if (fd!=fc) { clearInterval(it); fd.setAttribute("data-tags",tgs); } },0); }

CSS Syntax
The selector syntax for passages with specific tags is [data-tags~=tagname]. So, if you tag a bunch of passages with "dream", you can then apply specific CSS to just those passages like this:

[data-tags~=dream] {
  color: aqua;
  text-shadow: aqua 0 0 3px;
}
The preceding code will affect both the passage div and the body element. To select those elements separately, use syntax like this:
body[tags~=blood] {
  background-color:red;
  color: black;
}
.passage[tags~=blood] {
  border: 5px solid white;
  font-size: 110%;
  width: 30em;
}
Some variations on the selector syntax exists that you might find useful:
[data-tags*=swamp] for a passage whose tags contain "swamp" (such as "grayswamp" or "swampfort").
:not([data-tags~=gold]) for a passage which does not have the tag "gold".

And, of course, you can select elements of a matching passage <div> by combining selectors with ".body", ".body .internalLink" and such:

.passage[data-tags~=cave] .body .internalLink { color: gold; }

Caveat: all of this won't work for passage text displayed with the << display >> macro unless you use something like

If you like this code, consider using these macros that let you control tags inside the game.

*This is really just a workaround until browsers support CSS selector subjects. Ideally you could just do !body .passage[data-tags:], but alas, not this year.

pensive-mosquitoes