15
May '12

Expanding an Element to Fit Available Space with jQuery

In my opinion one of the big glaring fails in CSS is the lack of ability to make an element expand to fill the remaining space within its parent container. So often, particularly in mobile design, in order to build as flexible a layout as possible I want to let one element be the size it needs to be and have another fill the remaining space. That’s what this jQuery plugin does.
This version works for filling the remaining height, but I’m sure you can see how easy it is to change it to work for widths.

(function($) {
	$.fn.dynamicElement = function() {
		options = jQuery.extend({
			spacing: 20
		}, options);

		this.each(function() {
			var sibling_height = 0;

			$(this).siblings().each(function() {
				sibling_height += $(this).outerHeight(true);
			});

			var parent_height = $(this).parent().innerHeight();

			$(this).height(parent_height - sibling_height - options.spacing);
		});
	}
})(jQuery);

Options
spacing – adds an extra gap. Do bear in mind though that the position of this gap will be dependent on how you have aligned your elements.

Calling the Function

$('.element').dynamicElement();
$('.element').dynamicElement({ spacing: 50 });

Leave a Reply