Editable Style Blocks

We know that different HTML elements do different things. That’s obvious when we can see them. But some HTML elements operate behind the scenes and sometimes we just don’t think about them as being related to elements that are intended to be visual. But let’s take a little trip into making some elements visual that aren’t by default and how weird (and maybe useful!) it can get.

When you see some HTML like:

<p>I'm going to display this text.</p>

That’s pretty intuitive. Like, the browser is going to display that paragraph element of text.

But that paragraph exists in a larger HTML document, like:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>My Website</title>
</head>
<body>
  <p>I'm going to display this text.</p>
</body>
</html>

Why doesn’t “My Website” also display like the paragraph does? What’s so different about <title> and <p>. Well, that’s the nature of any code. Different things do different things. But in this case, we can trace why it doesn’t display pretty easily.

If we open this HTML document in a browser an inspect that <title> element, it will show us that the User Agent Stylesheet sets that element to display: none; Well that makes sense! That’s exactly what we use when we want to hide things entirely from sites.

What’s more, the <title> elements parent element, <head>, is also display: none;.

This is where it gets funny.

User Agent styles are very easy to override! Any value that comes from our CSS will override it. So let’s try this:

<style>
  head, title {
    display: block;
  }
</style>

LOLZ, there it is! Just like a paragraph:

And we have just as much control over it as anything else, meaning we can apply perfect styling to it:

And this can get even weirder… See that <style> block that is also in the <head>, we can’t see that for the exact same reason we couldn’t see the <title>, it’s display: none;. We can change that to make it visible also.

While we’re at it, we can make it look like it does in our code editor too by having it respect whitespace and use a monospace font:

head, title, style {
  display: block;
}
style {
  font-family: monospace;
  white-space: pre;
}

Ha! What the heck!

Now we can get one more step weirder. That style block? It can become editable, because that’s a thing any HTML element can do thanks to the contenteditable attribute.

<style contenteditable>
  ...
</style>

Now that visible <style> block can be edited just like it was a <textarea>, and the CSS applies immediately to the document.

Definitely one of the weirdest things HTML and CSS are capable of.

You might call this a CSS Quine (“a self-referential program that can, without any external access, output its own source.”). Alex Sexton published an example of this in 2013 and credits Anne van Kesteren and Mathias Bynens as prior art. I’ve seen Lea Verou use it to do live coding in conference talks!