Formatting with HTML and CSS

When you're working in ActionScript, there's more than one way to format text. The previous technique using ActionScript's TextFormat object works well when you're working on a project on your own. The properties and methods are familiar if you're used to working with Flash's Properties panel. Flash also lets you use the same formatting tools used by web designers: HTML (hypertext markup language) and CSS (Cascading Style Sheets). There are a few reasons why you might want to go this route for a project. Perhaps your project uses lots of text and it's already formatted using HTML. In some cases, you may be working on a large project where some people are responsible for generating the text and others are responsible for presenting it on the Web or in a Flash-based program.

Before you make a decision about using either HTML or CSS for your Flash formatting chores, it helps to understand their approaches to formatting text. HTML embeds formatting codes inside the text. For example, the second line in the tlfBanner text field of the previous example might look like this if you formatted in HTML:

<font face="Cooper Black" size="3"> Home of the <i>legendary</i> <b>Stutz
Bearcat</b></font>

When a web browser like Internet Explorer, Safari, or Chrome reads this text, it knows how to display the text in the browser window. It applies the formatting instructions and shows the text. It displays the proper typeface if it's available, otherwise it uses a substitute font. So HTML coding works fine from the audience point of view. For designers, it can be a bit of a pain. One of the problems of HTML coding is that the message gets a bit lost in the formatting tags. Complicated HTML coding is hard for human eyes to read, and that makes it easy to foul up. When you want to make changes, it's a lot of work to go in there and tweak all those bits of embedded code.

These days, the fashionable technique is to use CSS to format web pages. The underlying philosophy is that it's best to separate the formatting from the content. You create styles (type specs) for body text, major headlines, subheads, captions, and so forth. You store those definitions in a style sheet. Then, in the text, you tag different portions, indicating the styles they should use. In effect, you say: This is a major headline, this is body text, and this is a caption. When the browser goes to display your web page, it comes to the text tagged as a headline, and then it looks up the type specs in the style sheet. It does the same thing for the body text and the captions. From a designer's point of view, this system is a tremendous timesaver. If you want to change the caption style for a website that has 400 captioned pictures, all you need to do is edit one definition in the style sheet. If all those type specs were embedded HTML code, you'd need to make 400 separate edits.

There are two steps to using HTML encoded text in Flash. First, you need to create strings with the HTML codes embedded. Then you need to assign those strings to the htmlText property of the text field that will display the formatted text.

When you want to use HTML with its embedded codes in a Flash project, you need to build strings of text that include all the HTML codes. That means you end up with a lot of angle brackets, equals signs, and quotes inside your strings. The quotes present a small challenge, because your string needs to be wrapped in quotes when it's assigned to a variable or a text field (Strings). Fortunately, Flash accepts either single or double quotes. So if the HTML you're embedding looks like this line:

<p><font face="Cooper Black" size="3"> Home of the <i>legendary</i> <b>Stutz
Bearcat</b></font></p>

You can place it inside single quotes when you use it in Flash. For example, this statement assigns the HTML coded string to the txtBanner text field. It uses single quotes to define the string:

tlfBanner.htmlText = '<p><font face="Cooper Black" size=24> Home of the <i>
legendary</i> <b>Stutz Bearcat</b></font></p>';

HTML is like Flash in that it can use either single or double quotes in most places. Most of the time, you'll use double quotes, but be aware that you may sometimes see single quotes used to assign values in HTML code. In that case, you'd use double quotes to define your string in Flash.

Once you've stored your text in a string, you need to assign that string to a text field. Lucky for you, all TextField objects have an htmlText property, as shown in the code example above. It works just like the regular text property except that it understands how to read and then display text with HTML codes. As with any text field, you need to use the addChild() method to add your text field to the Display List and show it on the stage.

If there's one thing that made HTML king of the World Wide Web, it's the hyperlink. Hyperlinks are the threads that form that web. Click a linked word, and suddenly you're in a different part of the universe (or at least, the web). On Creating a Text Hyperlink, you saw how to create hyperlinks using the standard Flash authoring tools. The ability of text fields to use HTML encoded text also enables them to use HTML links. You create the links using the usual HTML codes: <a> anchor tags. Here's an example of an HTML hyperlink:

<a> href="http://www.stutzbearcat.net">click me</a>

Like most HTML tags, the anchor tag comes in pairs: <a>in between stuff</a>. The slash is the defining mark of an end tag. In HTML, you stuff that first tag with any necessary parameters. In this case, the parameter is a web address. The href stands for hypertext reference; the equals sign assigns a value to the reference inside double quotes. The specific value here is a web address. The words in between the two <a> tags, "click me," are visible in the browser window. Depending on the tag's formatting, they may appear underlined or highlighted in some way to show that they're a link.

Beyond that there's no magic to adding and using HTML hyperlinks in Flash. Here's an example of the same link included in a string that's passed to the htmlText property of a text field:

txtBanner.htmlText = '<p>To visit our website <a> href="http://www.
stutzbearcat.net">click me</a> </p>';

Flash Player isn't a web browser, so when your audience clicks the link, their browser opens and then loads the web page specified in the link. The link can just as easily point to a file on the local computer. In that case, instead of the http:// reference, you'd use a file:// reference.

Note

You can find HTML examples in 17-6_HTML_Text.fla in the Missing CD (www.missingmanuals.com/cds). There are a lot of HTML tags and keywords and Flash only works with some of them. A complete list of HTML tags that work with Flash is included in the help document ActionScript 3.0 Reference for the Adobe Flash Platform. Look up the Textfield class and its htmlText property.

CSS is the acronym for Cascading Style Sheets—an ingenious system for formatting HTML text. If you want to read up on how CSS works, you can get an excellent introduction in David Sawyer McFarland's CSS: The Missing Manual (O'Reilly). You need to have a basic understanding of CSS to use with Flash. This book provides a quick overview of CSS and an example or two to get you started.

CSS style sheets are a little like those wooden Russian dolls where one object is nested inside another. Starting from the outside and working in, here's what you find in a CSS style sheet. A style sheet is a list of formatting specifications. Each formatting spec has a selector that identifies the HTML tag that it formats. That tag could be the paragraph tag <p>, or the heading tag <h1>, or an anchor tag <a>. In CSS lingo, the formatting spec is called a declaration block. The declaration block is contained inside curly braces {}. Within those curly braces are specific declarations that define fonts, styles, colors, sizes, and all the other properties that can be defined in CSS. (Flash works with only some of these properties.) The declarations have two parts: a property and a value. So in CSS, if that property is font-size, then the value is a number representing point size. A CSS definition to format an <h1> heading tag might look like this:

h1 {
font-family: Arial;
font-size:18;
font-weight: bold;
color: red;
}

The first line has the selector for h1 headings, usually the biggest, boldest heading on a web page. The next four lines show pairs of properties and values. On the left side of the colon is the property, which is hyphenated if it's made up of more than one word. On the right side is the value assigned to that property.

In Flash, you can recreate the function of a CSS style sheet using the StyleSheet object. It gives you a way to create selectors and then assign values to the properties Flash recognizes. You can't use style sheets with TLF text, so here's Flash's version of the specification shown above using a Classic TextField.

1   var txtBanner:TextField = new TextField();
2   var styleSheet:StyleSheet = new StyleSheet();
3   var h1Style:Object = new Object();
4   var pStyle:Object = new Object();
5
6   h1Style.fontFamily = "Arial";
7   h1Style.fontSize = "24";
8   h1Style.fontWeight = "bold";
9   h1Style.color = 0x00FF00;
10
11  pStyle.fontFamily = "Arial";
12  pStyle.fontSize = "12";
13  pStyle.fontWeight = "normal";
14
15  styleSheet.setStyle("h1", h1Style);
16  styleSheet.setStyle("p", pStyle);
17  txtBanner.styleSheet = styleSheet;
18
19  txtBanner.x = 60;
20  txtBanner.y = 120;
21  txtBanner.width = 200;
22  txtBanner.height = 120;
23  txtBanner.autoSize = TextFieldAutoSize.LEFT;
24  txtBanner.background = true;
25  txtBanner.backgroundColor = 0xCDFFFF;
26  txtBanner.border = true;
27
28  txtBanner.htmlText = '<h1>Home of the legendary Stutz Bearcat</h1> <p>What
    can we do to put you into a Bearcat today?</p>';
29  addChild(txtBanner);

Here's a line-by-line rundown on the ActionScript. As in the other examples, line 1 creates the TextField object called txtBanner. The next three lines also create objects. Line 2 creates an instance of the StyleSheet class, and lines 3 and 4 create instances of the more generic Object class. You use these objects to hold the CSS declarations. That's exactly what's going on in lines 6 through 13. Values are being assigned to the h1Style object, and then the pStyle object.

Note that the property names have been changed slightly. That's because ActionScript jumps into action when it sees a minus sign (–). Instead, these properties eliminate the hyphen and use an uppercase letter for the word following the hyphen. So where the CSS property is named font-family, the ActionScript property is named fontFamily. Lines 15 and 16 use styleSheet's setStyle() method. The first parameter in the parentheses defines the selector: h1, the heading style, in line 15 and p, the paragraph style, in line 16. The second parameter in each case is the object that was created to hold the declarations. These are ActionScript's substitute for a declaration block with those paired sets of properties and values.

The styleSheet Object now has formatting instructions for two tags that it's likely to encounter in an HTML document. Line 17 assigns the styleSheet object to txtBanner's styleSheet property. Lines 19 through 26 are the ActionScript code that formats the text field. There's no CSS here; it's just straight ActionScript. Line 28 gets back into the CSS business. When you format with CSS, you pass the string to the text field using the htmlText property. The string itself is formatted like HTML, but instead of embedding formatting specs, it uses style tags. This little snippet uses two tags, first the <h1> tag for the heading, and then the <p> tag for its rather skimpy paragraph. With CSS, you need to assign the StyleSheet property before you put text in the text field. The last line adds the txtBanner to the Display List for the world to see. Figure 17-7 shows how the CSS-formatted text looks.

There are quite a few things missing from Flash's version of CSS. First of all, you can assign only one StyleSheet at a time to a text field's styleSheet property. One of the handy things about CSS is the way you use multiple style sheets for the formatting chores. Another feature missing from Flash's HTML capabilities is tables, causing moans among web-savvy designers. Web designers like to use tables to format and organize text and pictures.

One of the great features of CSS for designing web pages is that you can use a single external file (called a CSS style sheet) to format many web pages. Want to change the color of a heading? Simply change the definition in the style sheet, and that changes the look of all the web pages. You can use external CSS style sheets with Flash projects, too—just keep in mind the limitations of HTML and CSS in Flash mentioned in the previous section.

To start this exercise, you need a file that defines CSS styles. You can download 17-8flashText.css from the Missing CD site or create your own using a text editor. It's short and sweet:

p {
    font-family: Arial;
    font-size: 12px;
    font-weight: normal;
}
h1 {
    font-family: Arial;
    font-size: 24px;
    font-weight: bold;
    color: #00FF00;
}

This external CSS file defines the same CSS styles that were used in the previous example—the paragraph <p> tag and the heading 1 <h1> tag. Most CSS style sheets are more complicated than this, but as an example, this works just fine.

The ActionScript code that uses this external file needs to do a few things:

Here are the steps to load an external CSS style sheet and use the styles with code created in ActionScript:

  1. Create an instance of the URLLoader class.

    var loader:URLLoader = new URLLoader();

    The URLLoader class is used to load external files that reside on a computer or on the Internet.

  2. Register an event listener that triggers when the CSS file has completed loading.

    loader.addEventListener(Event.COMPLETE, loadCSSListener);

    The URLLoader class triggers an event when a file has loaded. When that event triggers, the function loadCSSListener() will run.

  3. Create an instance of the URLRequest class to identify the CSS file to be loaded.

    var request:URLRequest = new URLRequest("17-8flashText.css");

    The URLRequest class is used to identify files by filename and if needed a path. In this case, just the filename is used because 17-8flashText.css is to be stored in the same folder as the Flash project.

  4. Use the load() method to load the CSS file. Use "request" as the parameter for the load method.

    loader.load(request);

    Adding an extra blank line here sets the function for the event listener off from the rest of the code.

  5. Create the function that runs when the loader event is complete.

    function loadCSSListener(evt:Event):void {

    The rest of the statements in this exercise are part of this function, which ends with the closing curly bracket.

  6. Create an instance of the StyleSheet class.

    var cssFlashStyles:StyleSheet = new StyleSheet();

    The StyleSheet class holds CSS style definitions.

  7. Read the data in the external CSS file (flash_text.css) and store the data in the style sheet cssFlashStyles.

    cssFlashStyles.parseCSS(URLLoader(evt.target).data);

    The process of reading and processing the CSS definitions is called parsing. The method parseCSS is part of the StyleSheet class.

  8. Create an instance of the TextField class with the variable name "txtBanner."

    var txtBanner:TextField = new TextField();

    The text field txtBanner displays text stored in one of two properties—the text property or the htmlText property.

  9. Position and size the txtBanner, and then format the background and border.

    txtBanner.x = 60;
    txtBanner.y = 120;
    txtBanner.width = 200;
    txtBanner.height = 120;
    txtBanner.autoSize = TextFieldAutoSize.LEFT;
    txtBanner.background = true;
    txtBanner.backgroundColor = 0xCDFFFF;
    txtBanner.border = true;

    These statements aren't related to CSS, and their formatting applies to the entire text field.

  10. Add txtBanner to the Display List.

    addChild(txtBanner);

    Adding txtBanner to the Display List makes it visible on the stage.

  11. Assign the cssFlashStyles to the styleSheet property of txtBanner.

    txtBanner.styleSheet = cssFlashStyles;

    It may seem a little backward, but the style sheet needs to be applied before the text is assigned to txtBanner.

  12. Assign a string of text to txtBanner's htmlText property.

    txtBanner.htmlText = '<h1>Home of the legendary Stutz Bearcat</h1> <p>
    What can we do to put you into a Bearcat today?</p>';
    }

    The text assigned to the htmlText property of txtBanner is a string literal. The HTML tags <p> and <h1> are embedded within the string.

  13. Save your Flash file 17-7_External_CSS.fla in the same folder as the CSS file 17-8flashText.css.

    If you don't store the two files in the same folder, then you need to provide complete path information in the URLRequest, step 3.

When you test the movie, Control→Test Movie, you see text formatted as shown in Figure 17-5. The style definitions are identical in this example and the previous example, where CSS styles were written into the ActionScript code, so the results look the same.

In general, using external CSS style sheets gives you more flexibility, because you can change the appearance of text inside of your Flash project by simply editing the style sheet. As long as the name and location of the external CSS file stay the same, you don't even need to fire up Flash or ActionScript or republish your .swf files. How cool is that?