Setting a Flex component or control’s width to a percentage value

The following example shows how you can set a Button control to use percentage-based width and heights in ActionScript by using the [aptly named] percentWidth and percentHeight properties respectively.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/09/23/setting-a-flex-component-or-controls-width-to-a-percentage-value/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.events.SliderEvent;

            private function wSlider_change(evt:SliderEvent):void {
                button.percentWidth = evt.value;
                button.label = "w:" + button.width +
                                ", h:" + button.height;
            }

            private function hSlider_change(evt:SliderEvent):void {
                button.percentHeight = evt.value;
                button.label = "w:" + button.width +
                                ", h:" + button.height;
            }
        ]]>
    </mx:Script>

    <mx:ApplicationControlBar dock="true">
        <mx:Label text="percentWidth:" />
        <mx:HSlider id="wSlider"
                liveDragging="true"
                showTrackHighlight="true"
                minimum="10"
                maximum="100"
                change="wSlider_change(event);"
                snapInterval="1"
                tickInterval="10"
                labels="[10%,100%]" />

        <mx:Spacer width="100%" />

        <mx:Label text="percentHeight:" />
        <mx:HSlider id="hSlider"
                liveDragging="true"
                showTrackHighlight="true"
                minimum="10"
                maximum="100"
                change="hSlider_change(event);"
                snapInterval="1"
                tickInterval="10"
                labels="[10%,100%]" />
    </mx:ApplicationControlBar>

    <mx:Button id="button" label="Button" />

</mx:Application>

View source is enabled in the following example.

2 thoughts on “Setting a Flex component or control’s width to a percentage value

  1. if you set percentWith at 10% and then rise percentHeigth from 10% to 100%, button WIDTH change from 85 to 92!

    1. @Anonymous,

      Yes, because the Button’s label changes from “h:98″ to “h:100″ which causes the button to resize slightly to fit the additional character.

      Peter

Comments are closed.