One of the problems with CSS is that in involves a lot of copy&paste. Having multiple selectors which share a common property value (like a font color) is common, but in CSS you still need to have an individual color for each selector. So you end up with code that looks like this:
s|TextArea{
color:#eeeeee;
}
s|Button{
color:#eeeeee; /* the same color as above*/
}
Which is ok, but involves a lot of searching and replacing and careful analysis of the changes being made. I’ve been thinking about a way to put constants in there for a while and finally found a nice one today, while reading documentation for Flex 4.5. It’s really simple to use and has an added bonus – the compiler will make sure that the consts are actually defined, which should help with maintainability.
Defining the constants
Let’s start by defining the constants and their value. You need to create a new actionscript file (in my case style\StyleConstants.as), than throw away all the code that’s inside (eg. the package and class definitions), and define a const inside, we’ll use the file later.
/* file: style\StyleConstants.as */
private const someColorConstant:uint = 0xff0000;
Please notice that the variable can be private and will still work (it can also be public).
Putting Actionscript variables in CSS – PropertyReference
Looking at the Flex CSS documentation I’ve found that there’s a new keyword that you can use in Flex 4 CSS – PropertyReference. Since the docs say that “You can use document properties in your CSS” we’re going to do just that. The CSS class will be the modification of the one at the top, I’ll put it in style\Style.css and replace the colors with a pointer to the const declared above.
/* file: style\Style.css */
@namespace s "library://ns.adobe.com/flex/spark";
@namespace mx "library://ns.adobe.com/flex/mx";
s|TextArea{
color:PropertyReference("someColorConstant");
}
s|Button{
color:PropertyReference("someColorConstant");
}
Continue reading →