JavaScript

How to resize blocks equal in website

When we develop a website, many times we need to create several blocks that look the same and stay side by side, such as in the service section of a website where we have 6/9 blocks with the same style. However, when these blocks have varying content, they may not appear to be of equal height even when in the same row. But if we set the fixed height when styling, and if a block has more content, it overlaps outside the box.

How to resize blocks equal in website
Random block size

One solution is to use a JavaScript function for same height for all blocks. This function will find the maximum height among all boxes/blocks and set the height of the remaining blocks equal to it.

Below, I am demonstrating such a function using JavaScript and jQuery separately.

Steps to create the function:

  • First, create a function with any name; here I am using “reSizeArea,” which takes a parameter named “element” This parameter should be given the common class of the blocks.
  • Convert these classes into an array.
  • Run a map loop to find the height of all blocks.
  • Use the default JavaScript method “Math.max” to find the maximum height.
  • Iterate through the elements (classes) using a foreach loop and add the maximum height to the style of all blocks.

That completes the function creation. Now, select the common class of the blocks using a query selector and assign it to a variable. Trigger the function during load or resize events, passing the class variable as a parameter.

Resize blocks equal using javascript:

window.addEventListener('load', function () {
    function reSizeArea(elements) {
        var arr = Array.from(elements);
        var heights = arr.map(function (el) {
            return el.clientHeight;
        });
        var maxHeight = Math.max(...heights);
        elements.forEach(function (el) {
            el.style.height = maxHeight + 'px';
        });
    }

    if (window.innerWidth > 768) {
        var singleBlogElements = document.querySelectorAll('.HEARE_YOUR_BLOCK_CLASS_NAME');
        reSizeArea(singleBlogElements);
    }
});

Resize blocks equal using jQuery:

$(window).on("load", function () {
    function reSizeArea(e) {
        var arr = $.makeArray(e);
        var ah = $.map(arr, function (h) {
            return $(h).height();
        });
        var mh = Math.max.apply($(this).height(), ah);
        e.height(mh);
    }
    if ($(window).width() > 768) {
        reSizeArea($("..HEARE_YOUR_BLOCK_CLASS_NAME"));
    }
});
How to resize blocks equal in website
Equel height blocks

Note: In my code, I have resized for screens larger than 768, as resizing is unnecessary when blocks are not adjacent.

A self-taught Web Developer who loves to code, takes challenges, explores every day and lives a colorfull life.

Subscribe for Newsletter

Subscription Form