jump to navigation

The basics of using CSS in AS3 September 22, 2010

Posted by Tournas Dimitrios in Actionscript.
trackback

Cascading Style Sheets (CSS) are simple code sheets that are used to configure the visual look of pages and texts on the web. It could be used in Flash projects to format the way text fields look in Flash. Using CSS in Flash provides a number of advantages such as being able to customize your text in deeper ways (e.g. changing the the color of links) and to update the look of the text without having to go back to the source file.

This tutorial will teach you how to format some externally loaded text by using CSS.We are going to learn how to use external loaded CSS in AS3 by using it to format some text which we  also have loaded externally.This approach offers a lot of flexibility because you can modify the CSS file at any time and your text will look different, you can do that without republishing your swf file. Our CSS will be stored in a standard CSS style sheet. We are going to start by creating all the backend files and then code our project.

Creating the Text and CSS files :

The text which we will be using in this tutorial will be loaded externally. So we will create the file to host this text. Create a new folder for this project, and inside this folder create a blank text file using any simple text editor. Name this file myText.txt.

Inside this text file our text will be will HTML formatted so that we can manipulate it using CSS later. Simply paste the following inside your text file:

<p class="header">The basics of using CSS in AS3</p>

Visit this blog often. Check it out for the best AS3 tutorials on the internet.
<p class="footer">Click <a href="http://www.tournasdimitrios1.wordpress.com" target="_blank">here</a> for more info.</p>

Our text file is now ready, save and then close the file.

We will now create our CSS file, again use any simple text editor to create a blank text file and name it myStyle.css.If you are familiar with CSS you would know that CSS can format the way any HTML tag looks. So we are going to start off by making it change the way the <p> tag is displayed:

p {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 12px;
text-align:justify;
color:#666666;
margin-right:20px;
}

Not all regular CSS attributes are supported in Flash. The ones supported include text-align, font-size, text-decoration, margin-left, margin-right, font-weight, font-style, text-index, font-family, color, and display. You can learn more about these by checking Adobe’s online reference.

In addition to the ability to mass-format all instances of any HTML tag, we can target specific tags by using the “class” attribute which we have implemented in certain instances earlier in our HTML code. A class name starts with a dot. We are going to create a specific style class for the header paragraph and another for the footer paragraph.

p {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 12px;
text-align:justify;
color:#666666;
margin-right:20px;
}

.header {
font-size: 24px;
color:#E40018;
text-align:center;
}

.footer {
font-family:Geneva, Arial, Helvetica, sans-serif;
text-align:right;
} 

Finally, we are going to configure the way links look by using the anchor <a> tag. The style code below will change the color of the link and make it underlined when a mouse is hovered over it.

p {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 12px;
text-align:justify;
color:#666666;
margin-right:20px;
}

.header {
font-size: 24px;
color:#E40018;
text-align:center;
}

.footer {
font-family:Geneva, Arial, Helvetica, sans-serif;
text-align:right;
}

a {
color:#FF0000;
font-weight:bold;
}

a:hover {
text-decoration:underline;
}  

All of our external assets are now ready. Start up Flash, create a new FLA in AS3 format, save it in the same folder as your other assets, then right-click the only frame you have on your timeline and select Actions to open up the Actions panel and start coding your project.

We are going to write the ActionScript that will load our CSS file and use it to format some text loaded externally as well. This will be done in the following steps:

  1. Loading the CSS file , parse the CSS data and store it in an object
  2. Loading the text file.
  3. Creating the text field and applying the style sheet.
var css_loader:URLLoader = new URLLoader();
var txt_loader:URLLoader = new URLLoader();
var my_css:StyleSheet = new StyleSheet();
var my_txt:TextField = new TextField();

css_loader.load(new URLRequest("myStyle.css"));
css_loader.addEventListener(Event.COMPLETE, onCSSComplete);
function onCSSComplete(e:Event):void {
my_css.parseCSS(e.target.data);
txt_loader.load(new URLRequest("myText.txt"));

}

txt_loader.addEventListener(Event.COMPLETE, onTxtComplete);
function onTxtComplete(e:Event):void {
my_txt.styleSheet=my_css;
my_txt.htmlText=e.target.data;
addChild(my_txt);

my_txt.width=300;
my_txt.autoSize=TextFieldAutoSize.LEFT;
my_txt.wordWrap=true;

} 

HTML tags and CSS properties available in Flash 9 :

  • HTML tags supported :
Tag Description
Anchor tag The <a> tag creates a hypertext link and supports the following attributes: 

  • target : Specifies the name of the target window where you load the page. Options include _self , _blank , _parent, and _top . The _self option specifies the current frame in the current window, _blank specifies a new window, _parent specifies the parent of the current frame, and _top specifies the top-level frame in the current window.
  • >href : Specifies a URL or an ActionScript link event.The URL can be either absolute or relative to the location of the SWF file that is loading the page. An example of an absolute reference to a URL is http://www.adobe.com ; an example of a relative reference is /index.html . Absolute URLs must be prefixed with http://; otherwise, Flash treats them as relative URLs. You can use the link event to cause the link to execute an ActionScript function in a SWF file instead of opening a URL. To specify a link event, use the event scheme instead of the http scheme in your href attribute. An example is href=”event:myText” instead of href=”http://myURL&#8221; ; when the user clicks a hypertext link that contains the event scheme, the text field dispatches a link TextEvent with its text property set to “myText“. You can then create an ActionScript function that executes whenever the link TextEvent is dispatched. You can also define a:link , a:hover , and a:active styles for anchor tags by using style sheets.
Bold tag The <b> tag renders text as bold. A bold typeface must be available for the font used.
Break tag The <br> tag creates a line break in the text field. You must set the text field to be a multiline text field to use this tag.
Font tag The <font> tag specifies a font or list of fonts to display the text.The font tag supports the following attributes: 

  • color: Only hexadecimal color (#FFFFFF) values are supported.
  • face : Specifies the name of the font to use. As shown in the following example, you can specify a list of comma-delimited font names, in which case Flash Player selects the first available font. If the specified font is not installed on the user’s computer system or isn’t embedded in the SWF file, Flash Player selects a substitute font.
  • size : Specifies the size of the font. You can use absolute pixel sizes, such as 16 or 18, or relative point sizes, such as +2 or -4.
Image tag The <img> tag lets you embed external image files (JPEG, GIF, PNG), SWF files, and movie clips inside text fields. Text automatically flows around images you embed in text fields. To use this tag, you must set the text field to be multiline and to wrap text.The <img> tag supports the following attributes: 

  • src: Specifies the URL to an image or SWF file, or the linkage identifier for a movie clip symbol in the library. This attribute is required; all other attributes are optional. External files (JPEG, GIF, PNG, and SWF files) do not show until they are downloaded completely.
  • width : The width of the image, SWF file, or movie clip being inserted, in pixels.
  • height: The height of the image, SWF file, or movie clip being inserted, in pixels.
  • align : Specifies the horizontal alignment of the embedded image within the text field. Valid values are left and right . The default value is left .
  • hspace: Specifies the amount of horizontal space that surrounds the image where no text appears. The default value is 8.
  • vspace: Specifies the amount of vertical space that surrounds the image where no text appears. The default value is 8.
  • id : Specifies the name for the movie clip instance (created by Flash Player) that contains the embedded image file, SWF file, or movie clip. This is useful if you want to control the embedded content with ActionScript.
  • checkPolicyFile: Specifies that Flash Player will check for a cross-domain policy file on the server associated with the image’s domain. If a cross-domain policy file exists, SWF files in the domains listed in the file can access the data of the loaded image, for instance by calling the BitmapData.draw() method with this image as the source parameter. For more information, see the “Flash Player Security” chapter in Programming ActionScript 3.0.

Flash displays media embedded in a text field at full size. To specify the dimensions of the media you are embedding, use the <img> tag’s height and width attributes.

In general, an image embedded in a text field appears on the line following the <img> tag. However, when the <img> tag is the first character in the text field, the image appears on the first line of the text field.

Italic tag The <i> tag displays the tagged text in italics. An italic typeface must be available for the font used.
List item tag The <li> tag places a bullet in front of the text that it encloses. Note: Because Flash Player does not recognize ordered and unordered list tags (<ol> and <ul> , they do not modify how your list is rendered. All lists are unordered and all list items use bullets.
Paragraph tag The <p> tag creates a new paragraph. You must set the text field to be a multiline text field to use this tag. The <p> tag supports the following attributes: 

  • align: Specifies alignment of text within the paragraph; valid values are left , right , justify , and center .
  • class: Specifies a CSS style class defined by a flash.text.StyleSheet object.
Span tag The <span> tag is available only for use with CSS text styles. It supports the following attribute: 

  • class: Specifies a CSS style class defined by a flash.text.StyleSheet object.
Text format tag The <textformat> tag lets you use a subset of paragraph formatting properties of the TextFormat class within text fields, including line leading, indentation, margins, and tab stops. You can combine <textformat> tags with the built-in HTML tags.The <textformat> tag has the following attributes: 

  • blockindent : Specifies the block indentation in points; corresponds to TextFormat.blockIndent .
  • indent : Specifies the indentation from the left margin to the first character in the paragraph; corresponds to TextFormat.indent . Both positive and negative numbers are acceptable.
  • leading : Specifies the amount of leading (vertical space) between lines; corresponds to TextFormat.leading . Both positive and negative numbers are acceptable.
  • leftmargin : Specifies the left margin of the paragraph, in points; corresponds to TextFormat.leftMargin .
  • rightmargin : Specifies the right margin of the paragraph, in points; corresponds to TextFormat.rightMargin .
  • tabstops : Specifies custom tab stops as an array of non-negative integers; corresponds to TextFormat.tabStops .
Underline tag The <u> tag underlines the tagged text.
  • CSS properties :
  • These are all the CSS properties that can be manipulated from an external style sheet and with actionscript.

    CSS property ActionScript property Usage and supported values
    color color Only hexadecimal color values are supported. Named colors (such as blue) are not supported. Colors are written in the following format: #FF0000 .
    display display Supported values are inline , block , and none .
    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 .
    font-size fontSize Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.
    font-style fontStyle Recognized values are normal and italic .
    font-weight fontWeight Recognized values are normal and bold .
    kerning kerning Recognized values are true and false . Kerning is supported for embedded fonts only. Certain fonts, such as Courier New, do not support kerning. The kerning property is only supported in SWF files created in Windows, not in SWF files created on the Macintosh. However, these SWF files can be played in non-Windows versions of Flash Player and the kerning still applies.
    leading leading The amount of space that is uniformly distributed between lines. The value specifies the number of pixels that are added after each line. A negative value condenses the space between lines. Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.
    letter-spacing letterSpacing The amount of space that is uniformly distributed between characters. The value specifies the number of pixels that are added after each character. A negative value condenses the space between characters. Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.
    margin-left marginLeft Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.
    margin-right marginRight Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.
    text-align textAlign Recognized values are left , center , right , and justify .
    text-decoration textDecoration Recognized values are none and underline .
    text-indent textIndent Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.
Advertisements

Comments»

1. Ali Tavakoli - October 8, 2011

Thanks to ournasdimitrios1 for his clean and clear tutorial, very useful 🙂

I also got a news here that I thought would be so useful for all of us as Flash devs, Now that we are talking about TextField thought to let you know about a class that is so powerful and is extended from the Adobe TextField class itself.

It’s named TextArea which allows you every possible tags even your own custom tag and has much more abilities too.

Check out http://doitflash.com/ for more information.
It not only allows you to load different SWF files by calling different tags in line of your text but also you have much more control over your Text blocks and its contents… such as calling your custom functions right from your text blocks and passing multiple and different arguments through them; loading talking avatars, video players, buttons, slideshows and more… by calling their own tags and having full interaction between all of the loaded SWF modules and your text block. Check out the site for more information, downloading the platform is also free of charge 🙂


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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s