Tuesday, April 17, 2012

Using defaults.css in Flex Library Projects

In many of the development departments that I contract and consult with, it's very common to see the use of internal Flex Library projects to help separate the code base. However, it's rare that I see defaults.css and manifest.xml files in use with those projects. I thought I'd spend some time talking about them; what they do and why you should use them. This post will just deal with defaults.css and then I'll talk about manifest files in the next post.

When creating library projects to hold custom components, it's common to want to set default styles. This is even more important when writing to the Spark component architecture with skin files. You don't want the users of your components to have to add a properties or css to hook up the default skin files to their components.

I've seen some instances where the component developer sets these styles in the component's constructor. This seems to work fine with most styles, but it's problematic with skin files. For example, specifying a skin file in the component's constructor disables the ability to set a different skin as an attribute when defining the component as an MXML tag.

Another common approach is setting up static initializers in your components that look up style declarations and set defaults when certain declarations aren't found. I've seen no issues with this method but it's quite a bit more work involved compared to using a defaults.css.

Things would be much easier if you could specify a style sheet for your library projects to use. The problem is that there's no primary Application file, like in regular Flex projects, to hook a style sheet into. This is the problem that a defaults.css solves. If you've ever browsed the Flex SDK file system, you probably know that the SDK is really just a set of various library projects. The SDK libs that contain visual components (such as ths mx and spark libs) each have their own defaults.css file in the library source root. These are what gives the components their default look and feel without you having to specify any css yourself. This is a technique you can use with your own library projects.

The rules of using a defaults.css are very simple. And there's really only two rules.

  1. The file must be named "defaults.css" - all lower case.
  2. The file must be in the root of the project's source.
As for rule #2, if you're using FlashBuilder's default source directory, the file must be placed directly in the "src" folder. If you're using maven conventions, then it will probably be located in the "src/main/flex" package.

That's really all there is to it. You define default styles and skins for your project's components as normal.

1 comment: