javascript equal height blocks

Works in all modern browsers and IE9+.

javascript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
function heightsEqualizer(selector) {
 
    var elements = document.querySelectorAll(selector),
 
        max_height = 0,
 
        len = 0,
 
        i;
 
         
 
    if ( (elements) && (elements.length > 0) ) {
 
        len = elements.length;
 
     
 
        for (i = 0; i < len; i++) { // get max height
 
            elements[i].style.height = ''; // reset height attr
 
            if (elements[i].clientHeight > max_height) {
 
                max_height = elements[i].clientHeight;
 
            }
 
        }
 
 
 
        for (i = 0; i < len; i++) { // set max height to all elements
 
            elements[i].style.height = max_height + 'px';
 
        }
 
    }
 
}
 
 
 
if (document.addEventListener) {
 
    document.addEventListener('DOMContentLoaded', function() {
 
        heightsEqualizer('.js-equal-height');
 
    });
 
    window.addEventListener('resize', function(){
 
        heightsEqualizer('.js-equal-height');
 
    });
 
}
 
 
 
setTimeout(function () { // set 1 second timeout for having all fonts loaded
 
    heightsEqualizer('.js-equal-height');
 
}, 1000);

html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<div class="blocks">
 
    <div class="block js-equal-height">Lorem Ipsum text.<br />
 
        Lorem Ipsum text.<br />
 
    </div>
 
    <div class="block js-equal-height">Lorem Ipsum text.<br />
 
        Lorem Ipsum text.<br />
 
        Lorem Ipsum text.<br />
 
        Lorem Ipsum text.<br/>
 
    </div>
 
    <div class="block js-equal-height">Lorem Ipsum text.<br />
 
        Lorem Ipsum text.<br />
 
        Lorem Ipsum text.<br />
 
    </div>
 
    <div class="block js-equal-height">Lorem Ipsum text.<br />
 
        Lorem Ipsum text.<br />
 
        Lorem Ipsum text.<br />
 
        Lorem Ipsum text.<br/>
 
        Lorem Ipsum text.<br/>
 
    </div>
 
</div>

css:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
* {
 
    box-sizing: border-box;
 
}
 
 
 
.blocks {
 
    float: left;
 
    width: 100%;
 
}
 
.block {
 
    float: left;
 
    width: 20%;
 
    background: #ffa;
 
    padding: 10px;
 
    margin: 10px;
 
}

2 thoughts on “javascript equal height blocks”

  1. After an entire day of searching, finally found the solution. Thanks :) Works wonderfully with DOM content.

    Reply

Leave a Reply to Rahul Singh Cancel reply