Monthly Archives: January 2014

jQuery Lightbox

Creating a centered lightbox that dynamically resizes the image and maintains centering within the browser window is simple if you know the technique.  Hopefully this short article will save someone else the time I spent finding a solution.  I have tested the technique in the current (as of posting date) versions of IE, Firefox and Chrome. Note, however, that the JSFiddle example below does not work in IE.

While I have used jQuery in this example, CSS3 is the real hero and the technique itself is framework agnostic.  It should be noted however, that IE8 does not support the required CSS property.

As you will note in the code below, the technique uses an empty <div> that will overlay the viewport and display the desired image as its background.  This method allows us to use the CSS3 background-size property with the contain value that will scale the image with the window while maintaining aspect ratio.  Centering is provided by the background-position property as shown in the code above.

I have used jQuery to dynamically assign the value of the background-image property based on the href in the anchor tag.  This allows clients without JavaScript enabled to access the image as an ordinary link.  Of course, jQuery also provides the cool fading effect.  Most users will probably want to extend the functionality of this rudimentary lightbox using their framework of choice or even straight JavaScript.