Styling undefined tag names in HTML

20 Oct 2009

Realization after Molly Holzschlag’s presentation about HTML5 at today’s Geek meet:

You can use any tag name in HTML, and it will be part of the DOM and can be styled.

For example, the following HTML:

Some text in <red>another colour</red>!

…styled with the following CSS:

red { color: red; }

…gives the following result:

I have always somehow assumed that elements with unknown names (such as red) were stripped out and ignored by the browser, but obviously they aren’t (at least not in Firefox).

The nice thing with this is that you can already start using elements that are defined in HTML5 but that old browsers don’t recognize:

<header>
    <h1>My cat's home page</h1>
</header>
<p><red>Meow!</red></p>
<footer>
    <p>© 2009 My Cat</p>
</footer>

Here the content of the header and footer elements will be displayed and can be styled with CSS, even if the browser doesn’t know the semantics of them. Newer browsers and search engines can use them to provide a better user experience.

This may be old news to some, and I just realized it today! Well, I don’t claim to be an HTML expert either. I don’t know if any of this is standards-compliant and I’ve only tested it on Firefox.

Update Oct 21st

It works in Chrome as well.

In Internet Explorer (I tested IE6 and IE7), the <red> element is part of the DOM and I can retrieve it with document.getElementsByTagName('red'). I can set its style, but IE’s rendering engine ignores it.

As Robert Nyman mentioned in the comments, there is a workaround. It is as simple as it is unexpected. Just create elements of the types you need with Javascript:

<script>
document.createElement("header");
document.createElement("footer");
document.createElement("red");
</script>

Just creating elements, even without inserting them into the document seems to do some magic that kicks IE into handling the previously undefined elements.

Test file (includes the IE hack)

blog comments powered by Disqus