Thursday, July 16, 2009

Tip: Sizing the Silverlight control for FireFox and other browsers

Cross-browser compatibility is very important to us and we often test functionality in multiple browsers. It was disappointing when I found that my Silverlight 3 application was no longer rendering in FireFox 3. I tested it in Internet Explorer, Chrome, and everything else, and while FireFox would not throw an error and even let me right-click and see the "Silverlight" dialog, the contents of my control simply weren't displaying!

After asking on several forums and getting blank stares and looks like, "Is this guy kidding? It works FINE in FireFox" I finally was struck today with a thought and it turned out right.

I was trying to size the page to modestly fit within the viewing area of the browser, like this:

<style type="text/css">
#silverlightControlHost 
{
    width: 100%;
    height: 100%;
    text-align: center;
}
</style>
<div id="silverlightControlHost">
    <object id="silverlightObject" width="100%" height="80%" ...

The 80% was a hack. For some reason with absolute vs. relative positioning of DIVs, the percentage-based width/height breaks in IE and so 100% was extending off-screen due to our header div. Of course this didn't help me at all on FireFox, because it wasn't showing at all. The thought that hit me was if browsers are struggling with our complex master page layout, perhaps FireFox didn't like my percentages and was making the application impossibly small?

I tested my theory and swapped out the width/height with actual pixel values of 640 and 480 respectively. I refreshed the page and ... voila! there was my application, happy as a lark but small enough to fit on a Commodore 64 screen.

Fixed size just won't do it and I was tempted to do some server-side hack to emit the size dynamically when I realized my good friend, JQuery, could come to the rescue once again. The refined mark-up indeed has a fixed size:

<style type="text/css">
#silverlightControlHost 
{
    width: 100%;
    height: 100%;
    text-align: center;
}
</style>
<div id="silverlightControlHost">
    <object id="silverlightObject" width="1024" height="768" ...

But then I add a tiny little snippet that makes the world a better place:

<script type="text/javascript">
    $(document).ready(function() {
    $("#silverlightObject").height($("#silverlightControlHost").height());
    $("#silverlightObject").width($("#silverlightControlHost").width());
    });
</script>

It's simple. The DIV sizes itself fine, it's the object inside the div that was having problems. So, once the page is loaded, I just override the height/width parameters for the object to completely fill the parent div. Works like a charm, tested on IE 6, IE 8, FireFox 3, and Chrome. (OK, so the IE 6 testing proves that IE doesn't have a clue how to size DIVs, but at least it shows, albeit with some scrollbars).

Jeremy Likness