8.15. Applying CSS

Problem

You want to apply CSS (cascading style sheets) to a dynamic text field.

Solution

Use a StyleSheet object to load the CSS from an external file, and then apply it to the text field.

Optionally, use the TextLoader component.

Discussion

The StyleSheet class allows you to apply CSS to text fields in your Flash application. While there are several ways in which you can create and populate a StyleSheet object within Flash, the most useful is to load an external CSS document. You can define a CSS document using a standard text editor or a CSS editor such as Dreamweaver or Top Style.

After you’ve defined the CSS document, save it to the same directory to which you are saving the .swf file. Then, within Flash, use the following code:

	// Set the text field so that it can render HTML.
	tField.html = true;
	// Create a StyleSheet object.
	var cssStyles:TextField.StyleSheet = new TextField.StyleSheet();
	// Define an onLoad( ) event handler method for the style sheet so that it knows what to
	// do with the CSS once it has loaded.
	cssStyles.onLoad = function(bLoaded:Boolean):Void {
	  if(bLoaded) {
	     // Apply the style sheet to the text field.
	     tField.styleSheet = this;

	     // Assign the HTML text to the text field.
	     tField.htmlText = "HTML text";
	    }
	};
	// Load the CSS.
	cssStyles.load("CSS document");

As you can see from the code, you can apply a style sheet to a text field using the styleSheet property of the text field. You must apply the style sheet to the text field before you assign the ...

Get Flash 8 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.