Archive for May, 2009

Setting width and height in Flex using CSS

Saturday, May 9th, 2009

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 {
			super();
			// 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{
			super.styleChanged(styleProp);
			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.