Loading External CSS StyleSheets in Flash9 / AS3 / CS3

External CSS stylesheets can be used with flash AS3. This is possible with the StyleSheet class in AS3 and controls such as TextField have a property for the stylesheet.


var styles:TextField.StyleSheet = new TextField.StyleSheet();
styles.onLoad = function(success:Boolean):Void {
    if (success) {
        // display style names.
    } else {
        trace("Error loading CSS file.");

OR apply to a StyleSheet object that can be used for many controls


    import flash.display.Sprite;
    import flash.events.Event;
    import flash.net.URLLoader;
    import flash.net.URLRequest;
    import flash.text.StyleSheet;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;

    public class CSSFormattingExample extends Sprite
        var loader:URLLoader;
        var field:TextField;
        var exampleText:String = "<h1>This is a headline</h1>" +
            "This is a line of text. <span class="bluetext">" +
            "This line of text is colored blue.</span>";

        public function CSSFormattingExample():void
            field = new TextField();
            field.width = 300;
            field.autoSize = TextFieldAutoSize.LEFT;
            field.wordWrap = true;

            var req:URLRequest = new URLRequest("example.css");

            loader = new URLLoader();
            loader.addEventListener(Event.COMPLETE, onCSSFileLoaded);

        public function onCSSFileLoaded(event:Event):void
            var sheet:StyleSheet = new StyleSheet();
            field.styleSheet = sheet;
            field.htmlText = exampleText;

Flash is limited in CSS support and only supports CSS1 properties and a minimal amount for formatting.

Supported CSS properties

Flash Player supports a subset of properties in the original CSS1 specification (www.w3.org/TR/REC-CSS1). The following table shows the supported CSS properties and values as well as their corresponding ActionScript property names. (Each ActionScript property name is derived from the corresponding CSS property name; the hyphen is omitted and the subsequent character is capitalized.)

CSS property ActionScript property Usage and supported values
text-align textAlign Recognized values are left, center, right, and justify.
text-decoration textDecoration Recognized values are none and underline.
margin-right marginRight Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.
kerning kerning Recognized values are true and false.
letter-spacing letterSpacing Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.
font-family fontFamily A comma-separated list of fonts to use, in descending order of desirability. Any font family name can be used. If you specify a generic font name, it is converted to an appropriate device font. The following font conversions are available: mono is converted to _typewriter, sans-serif is converted to _sans, and serif is converted to _serif.
display display Supported values are inline, block, and none.

For an example of using styles on XML elements, see An example of using styles with XML.


29 Responses to “Loading External CSS StyleSheets in Flash9 / AS3 / CS3”

  1. felisan Says:

    nice blog.
    looking forward to read more!

    and sorry, but actionscript 3.0 is really hard to understand, I think.
    so here’s my rookiequestion.

    I’ve added this code to my file:

    var styles:TextField.StyleSheet = new TextField.StyleSheet();
    styles.onLoad = function(success:Boolean):Void {
    if (success) {
    // display style names.
    trace(“this is the styles name: “+this.getStyleNames());
    } else {
    trace(“Error loading CSS file.”);
    content of styles.css:
    body {
    background-color: #cccccc;
    width: 400px;
    height: 300 px;
    border: 1px solid #4b4b4b;
    margin: 10px auto;
    text-align: center;
    h1 {
    margin: 0;
    font-family: verdana, arial, sans-serif;
    color: #4c4c4c;
    font-size: 14px;
    font-weight: bold;
    h2 {
    color: #999999;
    font-family: verdana, arial, sans-serif;
    font-size: 12px;
    font-weight: bold;
    p {
    font-family: verdana, arial, sans-serif;
    color: #000000;
    font-size: 11px;
    p.Right {
    text-align: right;
    #content {
    text-align: left;
    background-color: #ffffff;
    padding: 10px;

    how do I actionscript a textfield, that uses this .css-file?

    thanks in advance

  2. drawk Says:

    Hey felisan. You are on the right track all you have to do now is set htmlText of your textbox to include spans or classes from your stylesheet. i.e.

    var label:TextField = new TextField();
    label.styleSheet = style;
    label.htmlText = “Hello World…”;

  3. RaQ Says:

    I’m receving an error when i compile the file …

    1046: Type was not found or was not a compile-time constant: Void.

    What can i do ?

  4. Charlie Szymanski Says:

    RaQ: Void needs to be lowercased in AS3… Use “void” instead.

  5. Jason F Says:

    How does this work with TextArea? I tried using setStyle(“textFormat”, myFomat) but I’m not getting anything.

  6. drawk Says:

    Hey Jason,

    Are you immediately setting it or doing it in the onload of the css file in flash? If you set it without waiting for it to load it will not whos.

    Also, setStyle is an older AS1 method. The above samples are as2 and for AS3 especially where you have StyleSheet classes that you set to the .styleSheet properties.

    Then you just use html tags like to set styles to in the TextAreas.

    # public function onCSSFileLoaded(event:Event):void
    # {
    # var sheet:StyleSheet = new StyleSheet();
    # sheet.parseCSS(loader.data);
    # field.styleSheet = sheet;
    # field.htmlText = exampleText;
    # }

  7. Louis Says:

    I’m looking at the as3 example starting on line 16. Will this cause an “Error 1095: The string literal must be terminated before the line break.”?

    Also, do you need to escape the quotes around “bluetext” in line 21 or does as3 somehow figure that all out?

  8. Thomas Says:

    i see to be having an issue using this code to format external text loads. is there an alternative code i need when trying to format external text? thanks.

    var external_txt:TextField = new TextField();
    var externalReq:URLRequest = new URLRequest(“aboutus.txt”);
    var externalLoad: URLLoader = new URLLoader();


    externalLoad.addEventListener(Event.COMPLETE, textReady);
    external_txt.text = event.target.data;

    external_txt.x = 104;
    external_txt.y = 140;
    external_txt.width = 522;
    external_txt.height = 272;


    var styles:TextField.styleSheet= new TextField.styleSheet();
    styles.onLoad = function(success:Boolean):void {
    if (success) {

    } else {
    trace(“Error loading CSS file.”);

  9. drawk Says:

    Hey Thomas,

    You need to set the text property of htmlText and then also when you have the styles object set it to the styles formatter.

    field.styleSheet = sheet;
    field.htmlText = exampleText;

    Or for your specific samples

    external_txt.styleSheet = styles;
    external_txt.htmlText = event.target.data;

  10. BeeBoy Says:

    I would like to know how to write to a file in actionscript.could someone illustrate that to me

  11. andreb Says:

    Hi, i’ve tried this example (exactly like it is) and it gives me no errors but the textfield doesn’t get formated! Anyone has any idea why this could hapen??


  12. robert Says:

    ok so i have this code(below) and i want to style the text, as in change the font, textcolor, size, etc. I dont know what i am doing and i am sooo frustrated, please help. cs3 as3

    var eMain_txt:TextField = new TextField();
    var eMainReq:URLRequest = new URLRequest(“text/eMain.txt”);
    var eMainLoad:URLLoader = new URLLoader();
    var eCap_txt:TextField = new TextField();
    var eCapReq:URLRequest = new URLRequest(“text/eCap.txt”);
    var eCapLoad:URLLoader = new URLLoader();


    eMainLoad.addEventListener(Event.COMPLETE, eMainReady);
    eCapLoad.addEventListener(Event.COMPLETE, eCapReady);
    up_btn.addEventListener(MouseEvent.CLICK, scrollUp);
    down_btn.addEventListener(MouseEvent.CLICK, scrollDown);

    eMain_txt.x = 245;
    eMain_txt.y = 80;
    eMain_txt.border = false;
    eMain_txt.width = 174.9;
    eMain_txt.height = 620;
    eMain_txt.wordWrap = true;
    eCap_txt.x = 36;
    eCap_txt.y = 223.3;
    eCap_txt.border = false;
    eCap_txt.width = 186;
    eCap_txt.height = 109;
    eCap_txt.wordWrap = true;


    function eMainReady(event:Event):void
    eMain_txt.htmlText = event.target.data;
    function eCapReady(event:Event):void
    eCap_txt.text = event.target.data;
    function scrollUp(event:MouseEvent):void
    eMain_txt.scrollV –;
    function scrollDown(event:MouseEvent):void
    eMain_txt.scrollV ++;

  13. ryan Says:

    robert you are almost there. You just need to now have a Stylesheet object that you can load from a css file or use flash to create (flash internally uses names without the “-” in them.

    Where loader.data is from the css file.

    var req:URLRequest = new URLRequest(“example.css”);
    loader = new URLLoader();
    loader.addEventListener(Event.COMPLETE, onCSSFileLoaded); loader.load(req);

    public function onCSSFileLoaded(event:Event):void
    var sheet:StyleSheet = new StyleSheet();
    field.styleSheet = sheet;
    field.htmlText = exampleText;

    Be sure your htmlText data has the HTML tags in it like etc. Also one thing about flash HTML is it only supports limited tags. See above for all the styles it supports.

    You can also look at wrapper or flashml to look at HTML to flash conversion which can handle more like divs and tables etc.

  14. humbleOne Says:

    ok so what i want to be able to do is load some xml data into flash, then be able to change it around in flash and then save the data over the original xml file.. (pretty much just a simple flash cms, using an xml file instead of a database)

    now i know actionscript very well, however thats about it.. don’t really know any other languages, like php, asp, etc etc..

    im guessing the easiest way to do this is to import the xml data, change it, place it within a variable, and then have some kind of script overwrite the oringal xml file with the variable.

    anyone able to help me out?

  15. drawk Says:

    Hey Humble,

    Here there are lots of ways. You will need external server script to help you save it to the file system (flash can’t do that by itself due to security).

    You could:
    – simple post it to a php or asp.net file that would then save the post variable to the file
    – use a service (web service or json service) to catch the remoting call and save it to disk
    – use a service to do a partial update (so you can stream the file and not kill the entire app when the file is writing)

    You can accomplish the first items with a URL loader with params.

    The second way you will need to have some service knowledge to pull off with NetConnection, PendingResult etc.

  16. HumbleOne Says:

    I appreciate the information but is it possible that you could further clarify the consept of server script or show me an example?Because the software i have to create is a selfcontain application which is suppost to be installed in the user’s machine, played and store results and user name with any internet connection.

    I am sorry for any incovinience is just that i’ve made so many attempts and now i am running out of time.

    please if methods u describe abouve doesn’t require interenet connection in order to work then please illustrate it to me

  17. HumbleOne Says:

    thank you in advance

  18. drawk Says:

    HumbleOne. The only way flash can save locally is by using an SWF2EXE like MDM zinc or Adobe AIR. Flash by itself cannot write to the file system for security reasons. But AIR sounds like a perfect candidate for you. It is meant for desktop flash and has access to system info and files.

  19. HumbleOne Says:

    thanxs i’ll have a look at that

  20. George Says:

    Dont suppose you know anything about implementing Line-height? Its supported within the TextFormat class (leading) so its possible within AS3 but the CSS property (line-height) is not supported when using an external style sheet.

    Ive found a few hacks around for AS2 but nothing on AS3 and wouldnt know where to start on migrating them.
    Any insight Id love to know,

    great site btw

  21. drawk Says:

    Hey George,

    I don’t think flash supports the line-height as it is not in the supported CSS list above. If is is there it will be lineHeight. Although not all hope is lost there are some great kits like flash wrapper and FlashML that convert HTML to flash and they have methods in there to get around some css that is not supported in flash (since flash css and html support is pretty ancient).

  22. pixelnickel Says:

    Hey guys, for line-height, try leading. (default is 2)


  23. yav Says:

    I’ve noticed an issue when using class in the CSS and then trying to style the hover, link and rollover effects of that class. Flash seems to hate that and none of the text is styled in the text field.



    .className a:hover


    .className a:link


    .className a:visited


    when importing into Flash it just ignores the entire style.

    I’ve also been using this nice little class that I wrote to handle my CSS loading:

    package com.barkley
    import flash.text.*
    import flash.events.*
    import flash.net.*

    public class cssStyle
    public var urlLoader:URLLoader
    private var css:StyleSheet
    private var callback:Function

    public function cssStyle(path:String, _callback:Function)
    callback = _callback

    urlLoader = new URLLoader()
    urlLoader.addEventListener(Event.COMPLETE, cHandler)
    urlLoader.load(new URLRequest(path))

    private function cHandler(e:Event):void
    css = new StyleSheet()


    public function getCSS():StyleSheet
    return this.css

    All works fine as long as I’m not using custom link styles in the CSS Class.

  24. Chris Says:

    Working on menu buttons that control the External Text with AS3. I have everything working with the main menu button, but when trying to get buttons with in a page to control the External Text i get an error and the site wont run.

    code for my a button that work in the main stage.


    function b1Listener(event:MouseEvent):void {

    Ok but now say you are on the artist page and want to display infomation on each artist once that artist is clicked. the button is not on the main stage its main stage then sections. this is the code i tried.


    function b8Listener(event:MouseEvent):void {

    Whats wrong?

  25. Gizmo Says:

    To yav:

    the order is wrong:
    a:link {}
    a:visited {}
    a:hover {}

    ‘hover’ should always be defined last …
    stupid … I know … but it should work

  26. Penis-Enlargement Says:

    Do u think its nice way to define? you should take care of some things in future posts.

  27. Acomplia Says:

    Acomplia represents one of the latest and indeed a most novel method for controlling body weight. Acomplia operates by being a cannabinoid receptor antagonist. This means that Acomplia prevents the normal action of endogenous cannabinoid in the brain from stimulating the so-called CB1 receptors. It would appear that these receptors stimulate appetite and therefore when they are “subdued” so is the need to eat.

  28. MikeS Says:

    Shut up, Acomplia…

    Anyways im having the same issue adreb(above) is having. While i did not use this tutorial verbatim, everything i have matches up logically, its returning no errors, BUT IT WON’T FORMAT THE TEXT!

    I am successfully importing both CSS and HTML files. (i know CSS is being imported by using trace)

    What could cause Flash to ignore CSS??

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: