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'
});

Sub Footer

About

Quirksmode is a fully responsive Universal React Application connected to a Headless CMS designed and developed by myself, web enthusiast and all round nice guy Dave. It was created to be my Portfolio and voice to the world.

All code has been hand written from scratch using Visual Studio. All of the opinions on this site are my own and do not represent those of my employer or colleagues.

+read more

Latest Tweets

+follow quirksmode_uk

Instagram

Contact

David Plunkett

Mobile Number: 07870257474

Email: david@quirksmode.co.uk

+make contact