How to Use Percentage Sizes for Your FancyBox CodeUnit 13 OCT 2012

I’m a huge fan of the jQuery-driven FancyBox and make use of it in just about all of my web development work.

This is a handy little trick to use percentage (%) values for a fancybox implementation’s width and height, thereby making it easier to specify a fancybox that will work regardless of screen size.

(If you are familiar with fancybox then you are aware that it requires height and width values to be passed to it as pixel values.)

Note that I’m assuming that you are making use of the wonderful jQuery JavaScript library here.

//setting a width of 90% and a height of 75%
var fbwidth = Math.ceil(($(document).width()*90)/100);
var fbheight = Math.ceil(($(document).height()*75)/100);

$('#versioninghistory').fancybox({'type':'iframe','autoScale':true, 'width': fbwidth, 'height':fbheight, 'centerOnScroll':true});

Looking at the snippet above, you’ll see that we are first calculating the pixel value of the desired percentage value based on either the screen width or height (using jQuery’s document related functions), and then passing it through to the fancybox declaration.


Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.

  • Actually the new Fancybox 2 does let you use percentages as width/height (according to the documentation), but no matter what I try I can’t get it to work. Very strange.

    • Doode

      It works if you pass the values as strings, including the pct sign (%).

      For example:

      width : ‘45%’,
      height : ‘70%’,