Adobe Flex 3 Help

Applying cascading style sheets

Text fields can contain either plain text or HTML-formatted text. Plain text is stored in the text property of the instance, and HTML text is stored in the htmlText property.

You can use CSS style declarations to define text styles that you can apply to many different text fields. CSS style declarations can be created in your application code or loaded in at run time from an external CSS file.

The flash.text.StyleSheet class handles CSS styles. The StyleSheet class recognizes a limited set of CSS properties. For a detailed list of the style properties that the StyleSheet class supports, see the flash.textStylesheet entry in the Flex ActionScript Language Reference.

As the following example shows, you can create CSS in your code and apply those styles to HTML text by using a StyleSheet object:

var style:StyleSheet = new StyleSheet();

var styleObj:Object = new Object();
styleObj.fontSize = "bold";
styleObj.color = "#FF0000";
style.setStyle(".darkRed", styleObj);

var tf:TextField = new TextField();
tf.styleSheet = style;
tf.htmlText = "<span class = 'darkRed'>Red</span> apple";

addChild(tf);

After creating a StyleSheet object, the example code creates a simple object to hold a set of style declaration properties. Then it calls the StyleSheet.setStyle() method, which adds the new style to the stylesheet with the name ".darkred". Next, it applies the stylesheet formatting by assigning the StyleSheet object to the TextField object's styleSheet property.

For CSS styles to take effect, the stylesheet should be applied to the a TextField object before the htmlText property is set.

By design, a text field with a style sheet is not editable. If you have an input text field and assign a style sheet to it, the text field shows the style sheet's properties, but the text field will not allow users to enter new text into it. Also, you cannot use the following ActionScript APIs on a text field with an assigned style sheet:

  • The TextField.replaceText() method
  • The TextField.replaceSelectedText() method
  • The TextField.defaultTextFormat property
  • The TextField.setTextFormat() method

If a text field has a style sheet assigned to it, but later the TextField.styleSheet property is set to null, the contents of both TextField.text and TextField.htmlText properties will add tags and attributes to their content to incorporate the formatting from the previously assigned style sheet. To preserve the original htmlText property, save it in a variable before setting the style sheet to null.