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

by Peter deHaan on September 23, 2007

in Button

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.

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

You can 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> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: