a responsive equal heights plugin

Overview

jquery.matchHeight.js

matchHeight makes the height of all selected elements exactly equal

brm.io/jquery-match-height

Demo - Features - Gallery - Install - Usage - Options - Data API
Advanced Usage - Tests - Known limitations - Changelog - License

Demo

See the jquery.matchHeight.js demo.

jquery.matchHeight.js screenshot

Modern browsers

In the years since this library was originally developed there have been updates to CSS that can now achieve equal heights in many situations. If you only need to support modern browsers then consider using CSS Flexbox and CSS Grid instead.

Features

  • match the heights for groups of elements automatically
  • use the maximum height or define a specific target element
  • anywhere on the page and anywhere in the DOM
  • responsive (updates on window resize)
  • row aware (handles floating elements and wrapping)
  • accounts for box-sizing and mixed padding, margin, border values
  • handles images and other media (updates after loading)
  • supports hidden or none-visible elements (e.g. those inside tab controls)
  • throttled to balance performance and smoothness
  • easily removed when needed
  • maintain scroll position
  • data attributes API
  • callback events
  • unit tests
  • module loader support
  • tested in IE8+, Chrome, Firefox, Safari, Android, iOS

Gallery

See how others are using jquery.matchHeight.js

Install

jQuery is required, so include it first. Download jquery.matchHeight.js and include the script in your HTML file:

<script src="jquery.matchHeight.js" type="text/javascript"></script>

You can also install using the package managers Bower and NPM.

bower install matchheight
npm install jquery-match-height

Usage

$(function() {
	$('.item').matchHeight(options);
});

Where options is an optional parameter.
See below for a description of the available options and defaults.

The above example will set all selected elements with the class item to the height of the tallest.
If the items are on multiple rows, the items of each row will be set to the tallest of that row (see byRow option).

Call this on the DOM ready event (the plugin will automatically update on window load).
See the included test.html for many working examples.

Also see the Data API below for a simple, alternative inline usage.

Options

The default options are:

{
    byRow: true,
    property: 'height',
    target: null,
    remove: false
}

Where:

  • byRow is true or false to enable row detection
  • property is the CSS property name to set (e.g. 'height' or 'min-height')
  • target is an optional element to use instead of the element with maximum height
  • remove is true or false to remove previous bindings instead of applying new ones

Data API

Use the data attribute data-mh="group-name" where group-name is an arbitrary string to identify which elements should be considered as a group.

<div data-mh="my-group">My text</div>
<div data-mh="my-group">Some other text</div>
<div data-mh="my-other-group">Even more text</div>
<div data-mh="my-other-group">The last bit of text</div>

All elements with the same group name will be set to the same height when the page is loaded, regardless of their position in the DOM, without any extra code required.

Note that byRow will be enabled when using the data API, if you don't want this (or require other options) then use the alternative method above.

Advanced Usage

There are some additional functions and properties you should know about:

Manually trigger an update

$.fn.matchHeight._update()

If you need to manually trigger an update of all currently set groups, for example if you've modified some content.

Row detection

You can toggle row detection by setting the byRow option, which defaults to true.
It's also possible to use the row detection function at any time:

$.fn.matchHeight._rows($('.item'));

Which will return an array of element selections for each row, see this thread for more information and an example.

Remove bindings

$('.item').matchHeight({ remove: true });

This will remove all bindings for the selected elements, from all groups.

Custom target element

$(function() {
	$('.item').matchHeight({
        target: $('.sidebar')
    });
});

Will set all selected elements to the height of the first item with class sidebar.

Custom property

$('.item').matchHeight({ property: 'min-height' });

This will set the min-height property instead of the height property.

Callback events

Since matchHeight automatically handles updating the layout after certain window events, you can supply functions as global callbacks if you need to be notified:

$.fn.matchHeight._beforeUpdate = function(event, groups) {
    // do something before any updates are applied
}

$.fn.matchHeight._afterUpdate = function(event, groups) {
    // do something after all updates are applied
}

Where event a jQuery event object (e.g. load, resize, orientationchange) and groups is a reference to $.fn.matchHeight._groups (see below).

Manually apply match height

$.fn.matchHeight._apply(elements, options)

Use the apply function directly if you wish to avoid the automatic update functionality.

Throttling resize updates

$.fn.matchHeight._throttle = 80;

By default, the _update method is throttled to execute at a maximum rate of once every 80ms. Decreasing the above _throttle property will update your layout quicker, appearing smoother during resize, at the expense of performance. If you experience lagging or freezing during resize, you should increase the _throttle property.

Maintain scroll position

$.fn.matchHeight._maintainScroll = true;

Under certain conditions where the size of the page is dynamically changing, such as during resize or when adding new elements, browser bugs cause the page scroll position to change unexpectedly.

If you are observing this behaviour, use the above line to automatically attempt to force scroll position to be maintained (approximately). This is a global setting and by default it is false.

Accessing current group bindings

$.fn.matchHeight._groups

The array that contains all element groups that have had matchHeight applied. Used internally for automatically updating on resize events, but you may modify this array if you need to manually access any groups (e.g. if you're deleting elements).

Tests

Open test/page/test.html in your browser to run unit tests via the jasmine test runner.

If you wish to contribute functionality to this project, you are encouraged to add new tests following the same conventions.

Run gulp test to run unit tests on multiple browsers and multiple resolutions, automatically through selenium.

Run gulp test:cloud to test on even more browsers via a cloud service (you will need to create a file called test/conf/private.conf.js with your cloud credentials that looks like this:

exports.config = {
    user: 'username',
    key: 'key'
};

Cloud browser testing for this project is provided by BrowserStack (which is free for open source).

Known limitations

CSS transitions and animations are not supported

You should ensure that there are no transitions or other animations that will delay the height changes of the elements you are matching, including any transition: all rules. Otherwise the plugin will produce unexpected results, as animations can't be accounted for.

Delayed webfonts may cause incorrect height

Some browsers do not wait for webfonts to load before firing the window load event, so if the font loads too slowly the plugin may produce unexpected results.

If this is a problem, you should call _update once your font has loaded by using something like the webfontloader script.

Content changes require a manual update

If you change the content inside an element that has had matchHeight applied, then you must manually call $.fn.matchHeight._update() afterwards. This will update of all currently set equal heights groups.

Also note that previous matchHeight bindings do not apply to new elements, even if they match the selector used. In this case you must remove the old bindings and add new ones, see this comment.

Changelog

To see what's new or changed in the latest version, see the changelog

License

jquery.matchHeight.js is licensed under The MIT License (MIT)
Copyright (c) 2014 Liam Brummitt

This license is also supplied with the release and source code.
As stated in the license, absolutely no warranty is provided.

Comments
  • $.fn update not firing

    $.fn update not firing

    I have a group which has content appended to it via AJAX. At the end of the images loading in the group, I show the content.

    If I use: $('.blocks').matchHeight(true); it works perfectly fine.

    If I use: $('.blocks').matchHeight(true); outside of the $.ajax call and try utilizing $.fn.matchHeight._update(); to trigger an update when the content is shown, it doesn't fire.

    I have a few other areas where the content is dynamically adjusted and I'd like to have the matchHeight updated but as of now, I can't do that. I assume sprinkling .matchHeight(true); 's everywhere is probably not the greatest option, so hopefully, I'm just missing something painfully obvious. :smile:

    investigate need-more-info 
    opened by wonderment 19
  • Height Property

    Height Property

    Hey there,

    Congrats for your plugin! You might consider setting the min-height param and not the height as it will allow more flexibility; just a quick hint :)

    Radu

    opened by raducretu 17
  • Plugin breaks on Safari(Windows/Mac) and Chrome(Mac)

    Plugin breaks on Safari(Windows/Mac) and Chrome(Mac)

    The plugin is great! However, there is the slight issue of it breaking for Safari (Windows/Mac) and Chrome(Mac)

    This is the way it should look: functioning

    This is what happens when it breaks:

    breaking

    and this:

    breaking 2

    It seems like it either doesn't calculate the heights at all, or calculates some of them and negates others.

    Safari for Windows 5.1.7. Chrome for Mac 31.0.1650.63

    Any fix would be greatly appreciated!!!

    Thanks.

    opened by markgenest 13
  • Safari: inconsistent height

    Safari: inconsistent height

    Hi! There's some issue with matchHeight plugin on my website in Safari (both Mac&iOS): the height calculated is too small and it varies on multiple page refreshes. screen shot 2014-07-02 at 16 21 27

    screen shot 2014-07-02 at 16 21 56

    This is a reference look in Chrome: screen shot 2014-07-02 at 17 05 15 Unfortunately I can't share URL yet since it's a local dev instance.

    opened by 2sheds 13
  • Some floating content inside one of the selected elements breaks equal height of subsequent ones

    Some floating content inside one of the selected elements breaks equal height of subsequent ones

    Hi there,

    first of all, this is by far the best equal heights plugin out there. So thank you.

    However, I've found this case (simplified in the jsfiddle) where it fails: http://jsfiddle.net/qoaa7d96/1/

    I broke this down to the floating figure in the first box being the cause. Switch off float: left for the figure and everything works as expected.

    Thanks for looking into it.

    Regards Danilo

    opened by jovilog 9
  • [0.5.2] matchHeight.js should set Items' `height` to `auto` while resizing to be responsive friendly

    [0.5.2] matchHeight.js should set Items' `height` to `auto` while resizing to be responsive friendly

    Scenario: Take for example the thumbnails component in Bootstrap 3.x. Create a responsive grid (.container-fluid) of thumbnails. Create 4 thumbnails inside a single row. Each thumbnail's content should be of different height, well, at least the first thumbnail on the left. Resize down until a thumbnail goes down onto a new line. It should get stuck at the right end of the first taller thumbnail. That's when I gave your plugin a shot to solve that issue.

    Since the maximum height is set on all thumbnails by matchHeight, when the window is being resized that maximum height does not change until a certain amount of time has passed (80ms by default) but a responsive grid such as bootstrap's keeps adapting without any delay and that has two visible downsides:

    1. The actual resizing is less fluid (sluggish) because of the repeated calculations the plugin has to make to update the height of each item. Setting a higher throttling delay doesn't help either because of downside number 2.
    2. When resizing a responsive grid whose content has fixed heights the results are not pretty until the actual resizing ends as is the case with bootstrap's responsive grid system.

    Solution:

    Set the items' height to auto when a resize event occurs and when the actual resize stops, calculate the max height and set it on every item. You should use underscore's _.debounce function for that. Something like this (snippet from an app I'm developing):

    var $win = $(window);
    $win.on('load resize orientationchange', _.debounce(resetItemsHeight, 500, true);
    $win.on('load resize orientationchange', _.debounce(matchItemsHeight, 500);
    

    I'll make a pull request when I enjoy some free time but right now I'm too busy.

    Despite this small issue, great plugin!

    opened by tubalmartin 9
  • Responsive breakpoint issue

    Responsive breakpoint issue

    Hi,

    I'm developing some site and I use your plugin. It's really great and this is the only one that works for me, but I have problem with it in one place. Maybe it's some bug or I do sth wrong. This is the situation: In one row, there are two blocks (A). In each block there are two blocks (B), in desktop view - one next to second.In tablet view, these inside blocks strething to full width (parent block A), so now they are one above other. The problem is, when resize window, heights doesn't change - it stays this same. But, when I refresh window, everything is OK (in tablet/desktop view), the plugin works well untill change from desktop/tablet view problem appears again.

    I use your plugin this way:

    $(window).load(function () { $.fn.matchHeight._apply('.row-blocks', true); });

    and for resize:

    var functions;

    function functionsResize() { $.fn.matchHeight._update();
    }

    $(window).resize(function () { clearTimeout(functions); functions = setTimeout(function () { functionsResize(); }, 200); });

    If I use plugin in basic way: $('.block').matchHeight('.row-blocks'); everything works well, but window freezes/lags during resizing.

    Sorry for my language mistakes, but I don't write in English a lot. Thanks in advance for any help. ;)

    height-issue2

    opened by chudy91 9
  • Overflow issue, only dissapears after page refresh

    Overflow issue, only dissapears after page refresh

    Hi,

    I'm using the matchHeight.js plugin in my Rails app:

    http://188.226.157.101/

    I've noticed an overflow issue, where text is overflowing it's div borders. Apparently this only appears on mobile screen sizes.

    I'm not sure if the error is caused by the Bourbon Neat grid framework or the matchHeight.js plugin.

    Anyone else encountered this issue?

    my repository is at:

    https://github.com/acandael/beautysalonapp2

    the matchHeight.js script is implemented at:

    https://github.com/acandael/beautysalonapp2/blob/master/app/views/homes/index.html.erb

    thanks for your help,

    Anthony

    opened by acandael 8
  • border styles not removed in IE8

    border styles not removed in IE8

    hey there. first off, i love the script. the row aware feature is amazing especially for responsive sites.

    i am having a strange issue however. in IE8 i am getting the following inline styles on my matchHeight elements.

    border-top: medium none; border-bottom: medium none;

    it seems .css("border-bottom",""); is not doing its job in IE8 for some reason. I will look into it, but just wanted to let you know.

    opened by Runeform 8
  • display: block

    display: block

    This works really well except if used on an element that utilizes the css "display" attribute. e.g., display: table; Since the display attribute gets overwritten by the javascript, it breaks the design (unless using !important). Perhaps an optional setting variable could be created for the display attribute?

    opened by allybee 8
  • matchHeight after Ajax call

    matchHeight after Ajax call

    Hi,

    I am a little new to jQuery, so apologies if this doesn't make sense!

    We are using an Ajax Layered Nav plugin to dynamically filter products in a WooCommerce project. Initially the shop items have matchHeight applied to them (works like a charm!), but after the Ajax call (no matter what we've tried!), we just can "access" the new content to re-apply the heights function.

    Currently we have been able to "hook into" the ajax function, and get things to happen (outside of the newly generated content) once it's done, but nothing we've tried has any effect on the new content.

    The code we're using (in our custom theme .js) is as follows:

    jQuery( "body" ).on( "aln_reloaded", function() {
        console.log("aln_reloaded done"); // works
    
        jQuery("#products").css({ backgroundColor: "red" }); // for testing - div just outside Ajax content - works
    
        jQuery(".products").css({ backgroundColor: "blue" }); // for testing - div just inside Ajax content - doesn't work
    
        jQuery.fn.matchHeight._update(); // doesn't work
    
        // Tried removing and then re-applying as per another post on the issue we read - doesn't work
        jQuery('.pw-item').matchHeight({ remove: true });
        jQuery('.pw-item').matchHeight(true);
    
    });
    

    Any help/advice/suggestions would be MUCH appreciated - thank you!

    question 
    opened by vmail79 7
  • documentation for _update and _applyDataApi

    documentation for _update and _applyDataApi

    Would be useful to add a little note in the docs about _applyDataApi().

    https://github.com/liabru/jquery-match-height/blob/master/jquery.matchHeight.js#L305

    In my experience, I had an infinite scrolling grid, and calling _update didn't fix the newly loaded elements.

    I had set them up using the data-mh api in the CMS.

    Calling $.fn.matchHeight._applyDataApi(); did do the trick, though.

    And perhaps adding a note to the _update to say this is also an option.

    opened by rtpHarry 0
  • Having multiple 'property' attributes

    Having multiple 'property' attributes

    Is it currently possible to set multiple property attributes?

    In this example: $('.item').matchHeight({ property: 'min-height' });

    Can I pass property an array? In my instance I need to set the height and the max-height.

    opened by skillmatic-co 0
  • Issue with nth-child and display property.

    Issue with nth-child and display property.

    Hi Firstly, love the plugin; it makes life so much easier.

    But I've ran into an issue.

    So I've got a content area, with each row having 2 columns of 50%. One column is an image, and one is content. Now, as per the design, the image alternates between left and right, so my idea is to have 3 columns of 50% in the HTML and use CSS nth-child to either hide the first or last column (the middle will always be content).

    This works perfectly, except with matchHeight as the third column is essentially pushed on to a new row due to the width settings.

    Is there a way to get it to work the way I have it, or should I just dynamically build the page?

    opened by Quin452 0
  • Overlapping elements

    Overlapping elements

    Hi there,

    Great plugin first of all. I have used it for many projects with no issue.

    However this is the first time I've used it for an e-commerce site with products being added all the time. My problem is that sometimes the elements overlap and the page needs a refresh for the plugin to work. It doesn't happen every time.

    It starts to do it's job then stops further down the page (please see attached screenshot as example).

    The code used is below:

    $(document).ready(function() {
    	$(function() {
    		$('#product_listings .listing').matchHeight();
    		$('#product_listings .listing .img_wrapper').matchHeight();
    	});
    	// $.fn.matchHeight._update();
    });
    

    I use one match height for the whole element and one for the image inside each element.

    You'll see $.fn.matchHeight._update(); is commented out because I tried this with no luck. Unless I'm using it wrong?

    Any ideas?

    Screen Shot 2019-10-23 at 17 14 39

    Thanks,

    Jack

    opened by jacklinwood 2
  • A different, faster approach?

    A different, faster approach?

    Hey all, I was using this library for a while until I realized yesterday I could use the ResizeSensor class from the css-element-queries library to achieve the same results. I can't tell if it's faster or not though, but it seems like unless something like this is already being done under the hood of this library then it has to be faster.

    I'm not quite sure how ResizeSensor does the magic it does, but it provides a hook into a very fast and reliable individual element resize event. Here's a jsfiddle illustrating what I mean. The way I have done it there makes some assumptions as it depends on the user setting up their varying-height columns to contain a single element and for that single element's height to be accurately represented by the clientHeight variable (i.e. no borders).

    However, despite dealing with those assumptions, I think it might be faster than this library. Am I wrong? Are you all already doing something like this?

    Also, sorry if this is the wrong place to post a question like this. Please let me know where I should post it though!

    opened by johntdowney 0
Owner
null
Drag and drop library for two-dimensional, resizable and responsive lists

GridList Drag and drop library for a two-dimensional resizable and responsive list of items Demo: http://hootsuite.github.io/grid/ The GridList librar

Hootsuite 3.6k Dec 14, 2022
Gmail-like client-side drafts and bit more. Plugin developed to save html forms data to LocalStorage to restore them after browser crashes, tabs closings and other disasters.

Sisyphus Plugin developed to save html forms data to LocalStorage to restore them after browser crashes, tabs closings and other disasters. Descriptio

Alexander Kaupanin 2k Dec 8, 2022
A lightweight jQuery plugin for collapsing and expanding long blocks of text with "Read more" and "Close" links.

Readmore.js V3 alpha I am deprecating the 2.x version of Readmore.js. A new version is coming soon! Check it out and help me test it! Readmore.js A sm

Jed Foster 1.5k Nov 30, 2022
BetterDiscord plugin to see what your friends are playing across platforms, all on Discord

CrossPlatformPlaying A plugin that brings Rich Presence to games that don't support it, and lets you see what your friends are playing even if they tu

Giorgio 38 Dec 12, 2022
An easy to use, yet advanced and fully customizable javascript/jQuery paginator plugin

anyPaginator An easy to use, yet advanced and fully customizable Javascript/jQuery paginator plugin. anyPaginator is a spinoff of the anyList project

Arne Morken 2 Feb 17, 2022
yt-dlp extractor plugin for DisTube.js.org.

yt-dlp extractor plugin for DisTube.js.org.

DisTube 6 Jul 17, 2022
A feature rich message noting plugin for Cumcord

Sperm Bank A feature rich message noting plugin for Cumcord. Features The ability to add messages to a virtual "account" The ability to make multiple

SwishyPlugs 8 Nov 30, 2022
Slide-element - A ~700 byte Promise-based library for animating elements with dynamic heights open & closed. Basically, a modern variant of jQuery's slideUp(), slideDown(), and slideToggle().

slide-element A tiny, accessible, Promise-based, jQuery-reminiscent library for sliding elements with dynamic heights open & closed. To see it in acti

Alex MacArthur 165 Dec 12, 2022
Responsive Tabs is a jQuery plugin that provides responsive tab functionality.

Responsive Tabs is a jQuery plugin that provides responsive tab functionality. The tabs transform to an accordion when it reaches a CSS breakpoint. You can use this plugin as a solution for displaying tabs elegantly on desktop, tablet and mobile.

Jelle Kralt 537 Dec 8, 2022
A customizable, modular, responsive, lightbox gallery plugin.

lightGallery A customizable, modular, responsive, lightbox gallery plugin for jQuery. Demo JQuery lightGallery demo. Codepen demo Main features Fully

Sachin N 5.6k Jan 4, 2023
Elegant, responsive, flexible and lightweight modal plugin with jQuery.

iziModal Elegant, responsive, flexible and lightweight modal plugin with jQuery. izimodal.marcelodolza.com Fast Responsive Animated Lightweight Custom

Marcelo Dolza 2.1k Dec 30, 2022
A Lightweight Responsive jQuery Tooltip Plugin

tipso A Lightweight Responsive jQuery Tooltip Plugin There is also a Wordpress version of this plugin. Get it here Getting started Include jQuery <scr

Bojan Petkovski 325 Dec 21, 2022
jQuery plugin to fire events when user's cursor aims at particular dropdown menu items. For making responsive mega dropdowns like Amazon's.

jQuery-menu-aim menu-aim is a jQuery plugin for dropdown menus that can differentiate between a user trying hover over a dropdown item vs trying to na

Ben Kamens 7.7k Dec 30, 2022
An awesome, fully responsive jQuery slider plugin

FlexSlider 2.7.2 http://www.woocommerce.com/flexslider/ - Copyright (c) 2015 WooThemes Releases The master branch of this repository is always the lat

WooCommerce 4.9k Jan 3, 2023
:snowboarder: A responsive slider jQuery plugin with CSS animations

A responsive slider jQuery plugin with CSS animations Animations from animate.css Online demo Visit plugin website. Appszoom for developers also uses

Joan Claret 58 Dec 12, 2022
Elegant, responsive, flexible and lightweight notification plugin with no dependencies.

iziToast Elegant, responsive, flexible and lightweight notification plugin with no dependencies. izitoast.marcelodolza.com Fast Responsive Animated Li

Marcelo Dolza 2.5k Jan 2, 2023
Unite Gallery - Responsive jQuery Image and Video Gallery Plugin. Aim to be the best gallery on the web on it's kind. See demo here:

##Unite Gallery - Responsive jQuery Gallery Plugin Product Link: unitegallery.net This gallery has commercial versions for: WordPress , Joomla! , Pres

Max Valiano 531 Oct 24, 2022
jQuery plugin to make HTML tables responsive

FooTable V3 This is a complete re-write of the plugin. There is no upgrade path from V2 to V3 at present as the options and the way the code is writte

FooPlugins 2.1k Dec 19, 2022
Easy responsive tabs - is a lightweight jQuery plugin which optimizes normal horizontal or vertical tabs to accordion on multi devices

Easy responsive tabs - is a lightweight jQuery plugin which optimizes normal horizontal or vertical tabs to accordion on multi devices like: web, tablets, Mobile (IPad & IPhone). This plugin adapts the screen size and changes its action accordingly.

Samson Onna 600 Dec 8, 2022
Responsive navigation plugin without library dependencies and with fast touch screen support.

Responsive Nav Responsive navigation plugin without library dependencies and with fast touch screen support. Responsive Nav is a tiny JavaScript plugi

Viljami Salminen 4.1k Dec 29, 2022