Flash support for CSS

While recently working with Flash to produce wireframes, I found out Flash MX 2004 has support for reading external CSS files. I’ve known about the TextFormat object as a way of formatting text fields in Flash for some time, but I never knew that you could just read in an external CSS file to do the same thing. While Flash only supports a limited subset of CSS, it does support those features reliably (Actionscript.org’s tutorial below lists the supported features).

This is useful in many ways, like if you want to roll out the same flash piece across different sites, or different parts of a site with different presentational schemes. Or if you re-skin a site, you can just change the CSS and the flash will reflect those changes, without making any edits to the Flash itself. Or if you’re just like me, and you like working with CSS. This makes things like the underlining of links (especially on hover) really easy.

A short example of the relevant code (where there is an external CSS file in the same location as the flash called “sample.css”:

var myCSS = new TextField.StyleSheet();
var cssURL = "sample.css";
myText = "<p class='headline'>Lorem ipsum</p>";
myText += "<a href='http://www.lipsum.com/'>Lorem ipsum</a>";
myText += " dolor sit amet, consectetuer adipiscing elit.";
myText += "Cras molestie tempor odio. Cras facilisis.";
myText += " Vivamus est mi, fringilla nec...";
myCSS.load(cssURL);
myCSS.onLoad = function(success) {
    if (success) {
        myTextField.styleSheet = myCSS;
        myTextField.text = myText;
    }
};

This info comes courtesy of:

Update - 11/05/2006

Okay, here’s the code in action (with a few little extra tweaks for demonstration purposes):

[kml_flashembed movie="/experiments/flash-css/flash-css.swf" width="310" height="150" /]

If you want to check out how it all works, the Flash file is here and the CSS examples are here and here.

3 comments

  1. That’s pretty cool – how bout a little inline demo hey? :)

  2. Okay, I’ve added a little demo, just for you, Mr Speaker. You may also recognise Stylesheet 2.

  3. My demand is popular! I’m going to have to start demanding more stuff!

    Stylesheet two does look quite attractive. Courier New is WAY better than the Comic Sans I intended to use….