Setting width and height in Flex using CSS

In the current version of Flex (3) it’s not possible to set width and height using CSS. The application I’m working on has a lot of screens containing a lot of TextInput fields. I want to be able to control the width and height of these text fields using CSS.

Sean Christmann has a nice solution for this. He uses HBox, I’ll use TextInput as an example:

package com.yourpackage {
	import mx.controls.TextInput;
	import mx.styles.StyleManager;

	public class ExtTextInput extends TextInput {
		public function ExtTextInput():void {
			// Default styleName for this component
			this.styleName = "extTextInput";

		 * This method makes styles "width", "height", "percentWidth", "percentHeight", "x", "y" and "visible"
		 * valid from css.
		override public function styleChanged(styleProp:String):void{
			if(!styleProp || styleProp == "styleName"){
				//if runtime css swap or direct change of stylename
				var classSelector:Object = StyleManager.getStyleDeclaration("." + styleName);
				if(classSelector != null){
					applyProperties(classSelector, ["width", "height", "percentWidth", "percentHeight", "x", "y", "visible"]);
		private function applyProperties(styleObj:Object, arr:Array):void{
			for each (var item:String in arr){
				var prop:Object = styleObj.getStyle(item);
				if(prop != null) this[item] = prop;


As the implementation extends the standard TextInput it will behave just like the standard TextInput. Databinding, runtime style changes… it all works.

The code sets a default styleName for the component, the style could look like this:

.extTextInput {
	percentWidth: 100;
	height: 18;

Of course you can set a different styleName while declaring the component in your application.

This entry was posted in Coding, Flex. Bookmark the permalink.

2 Responses to Setting width and height in Flex using CSS

  1. Alex says:

    I’m using exactly the same technique to extend the Button class. I’m loading different compiled CSS at runtime to change the size of the button. When I load a CSS without any width and height properties, the width and height do not revert to the default values. That is, the button does not automatically resize to fit the text of the label. I tried changing the IF statement in applyProperties to

    if (prop != null)
    this[item] = prop;
    this[item] = 0;

    but my button becomes invisible when I don’t specify width and height in the CSS. Any suggestion?

  2. Mark says:

    I’ve tested the code above also for extending the button class. If I don’t specify width and height it picks the default. Flex SDK 3.4

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>