Main Navigation

Main Content

jQuery: Fix Gaps Plugin

jQuery Featured Image

The Problem

While building a website recently I came across a very strange problem where gaps would appear when trying to float divs left and right of different heights. For some really strange reason, which I believe to be a bug, the divs don’t stack correctly and leaves gaps which is far from ideal. It’s quite hard to explain so I have set up a Fiddle which should clearly highlight the issue:

Fiddle to show the floating div gap problem

The Solution

I originally played around with the masonry and isotope plugins, which kind of did the job, but I found them way too powerful for what I needed and did not work too well when resizing the window. Instead I decided to write my own plugin which is pretty simple, it basically works out the height and Y coordinate of each div and adjusts the Top value accordingly.

You can download the Fix Gaps plugin here

I used quite generic class names for the defaults: module for the div’s and left and right to add the relevant float direction, but you can change these to whatever you want when you run the plugin. You can call the plugin like this (be sure to target the parent wrapper div, in this example it has the ID #fixGaps):

//#fixGaps is the main wrapper id, you can change this to anything, to use my default class names use this:
$('#fixGaps').fixGaps();

// You can use your own custom classes by updating the options and calling the plugin like this:
$('#fixGaps').fixGaps({
    module: '.module',
    leftModule: '.left',
    rightModule: '.right'
});
comments powered by Disqus

Sub Footer