Two columns with varying item counts but equal overall height

Wondering how to create a grid in HTML and CSS with columns of varying heights?

I'm trying to find a way to make the shorter column stretch to match the height of the taller one. I attempted using JavaScript but wasn't satisfied with the results, especially since the tallest column may not have the most rows. Additionally, different content lengths can result in boxes with varied heights.

I'm open to different markup approaches - currently using two side-by-side lists, though I'm considering a table or another method. However, simply using rowspan doesn't seem like it will suffice as it would only create one box much larger than the rest. This issue seems common - any effective solutions out there?

Answer №1

In this scenario, Javascript is likely the best solution. Personally, I would recommend utilizing percent-height for the elements within the lists.

  • Start by calculating how many elements are in each list.
  • Divide 100 by that number (can be tricky with values like 3, 6, etc)
  • Assign a percentage height to each element
  • Remember to also set the height on parent elements for percentages to function correctly

Answer №2

Check out this jQuery solution: http://jsfiddle.net/hunter/sG39d/

Adding top and bottom margins as well as padding to the li elements can make things a bit more complex.

$(function() {
    var $tallest = null;
    var $ul = $("ul");

    $("ul").each(function() {
        if ($tallest == null || $(this).height() > $tallest.height()) {
            $tallest = $(this);
        }
    });
    var height = $tallest.height();
    $ul.not($tallest).each(function() {
        var update = height / $(this).find("li").length;
        $(this).find("li").css("height", update);
    });
});​

Answer №3

After analyzing your code snippet:

let columnHeights=[], count=0, columns=[];

$('ul').each(function () {
    columns.push(this);
    let height = 0;
    $(this).find('li').each(function() {
        height += $(this).innerHeight();
    });
    columnHeights.push(height);
    count++;
});

let maxHeight = Math.max.apply(null, columnHeights);

for(let j=0; j<columns.length; j++) {
    let difference = Math.floor((maxHeight - columnHeights[j]) / $(columns[j]).find('li').length);
    $(columns[j]).find('li').each(function() {
        $(this).css('height', $(this).innerHeight() + difference);
    });
}

Answer №4

After spending some time on it, I have finally put together the Fiddle and the JS-Code:

My approach considers the relative size of the elements and stretches them proportionally. For instance, a div that originally occupied 50% of the space will still maintain that percentage after being stretched in the ul.

(There may be challenges when dealing with padding and borders. If anyone has a solution for this, I would love to hear it!)

JS:

$(function() {
    var $allUl = $('ul');
    setNewPercentages($allUl);

    function getTallestUl($uls) {
        var max = 0;
        var $ulTallest;

        $uls.each(function(i,e) {
            console.log( $(this).height() > max);
            if( $(this).height() > max) {
                $ulTallest = $(this);
                max = $(this).height();
            }
        });

        return $ulTallest;
    };

    function adjustPercentages($ul) {
        $ul.find('li').each( function(i,e) {
            var $this = $(this)
            ,   ulHeight = $ul.height()
            ,   liHeight = $this.height()
            ,   percentage = (liHeight / ulHeight * 100);

            $this.css('height', percentage + '%');
        });
    };

    function setNewPercentages($uls) {
        var $tallest = getTallestUl($allUl).addClass('tallest');
        var heightTallest = $tallest.height();

        $uls.not('.tallest').each(function(i,e) {
            adjustPercentages($(this));
            $(this).css('height', heightTallest);
        });
    };
});​

Fiddle

Answer №5

Perhaps this solution could be effective.

<table border="1">
<tr>
<td>
<table border="0">
<tr><td>data</td></tr>
<tr><td>data</td></tr>
<tr><td>data</td></tr>
<tr><td>data</td></tr>
<tr><td>data</td></tr>
</table>
</td>
<td>
<table border="0" cellpadding="5">
<tr><td>data</td></tr>
<tr><td>data</td></tr>
<tr><td>data</td></tr>
<tr><td>data</td></tr>
</table>
</td>
</tr>
</table>

Answer №6

Regrettably, achieving this is quite a challenge... perhaps you could consider utilizing these : faux columns

Answer №7

What do you think of this suggestion?

<table>
  <tr>
    <td>
      <div>Element1</div>
      <div>Element2</div>
      <div>Element3</div>
    </td>
    <td>
      <div>Element1</div>
      <div>Element2</div>
      <div>Element3</div>
      <div>Element4</div>
      <div>Element5</div>
    </td>
  </tr>
</table>

By using this method, both columns will maintain equal height. However, the contents in the shorter column may not expand to fill the empty space. It might be necessary to implement a Javascript solution for that.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Resizing input fields with Bootstrap 4

Is there a way to make form elements stretch to the whole row width in Bootstrap 4? The current arrangement looks quite messy: http://prntscr.com/id6pfm Here is the HTML: <div class="jumbotron vertical-center"> <div class="container-flu ...

Tips for implementing a for loop within a Bootstrap-Popover using JavaScript

After spending several days searching for a suitable example to no avail, I decided to bring my specific use case to SO. I currently have three Bootstrap 5 cards. https://i.sstatic.net/zDVOF.png I am looking to create Popovers for each card, with the po ...

Retrieve 2 values from a JSON array in a Node.js environment

Can someone assist me in extracting two values from my JSON array? Here is a link to the array: http://pastebin.com/tm5StsZ3 I am looking to retrieve both an ID and a key from these arrays. Any help would be greatly appreciated. I am currently working wit ...

Adjusting Headers Using Buttons

Having some issues with my JavaScript code. I'm trying to achieve a specific functionality where clicking the "Modify HTML content" button changes the h1 heading from "The Original Content" to "The New Content", and vice versa on subsequent clicks. Si ...

Is there a way to create an input mask that looks similar to this format --:--:--?

Is there a way to format an input in React to accept numbers in the format --:--:-- as 99:99:99 without using any plugins? Unfortunately, I am not sure how to achieve this with a simple input field. However, here is a snippet of code that I tried: <Tex ...

A guide to effortlessly importing JSON data with Svelte

During my recent testing, I have successfully utilized the below code to work with a component: <script> import x from "/path/to/x.json" </script> This code snippet effectively loads the json file into the variable x. Now my objecti ...

Is there a way to retrieve the original value of the substr value?

I successfully retrieved the correct value using the substr() method, but I am facing difficulty in getting back the original value. Can someone please guide me on how to achieve this? For example: "AAAAAA" -> AA... but I am unable to revert from AA.. ...

Validation for HTML5 does not appear when inputmask is used for entering mobile numbers

One problem that I have encountered is when using the input type = "text" with required = "required" for a mobile number along with an input mask. In this scenario, if a user does not enter any value, the HTML5 validation message does not appear. Instead, ...

What steps do I need to follow to send a POST request using JavaScript in Django while including the CSRF token?

I've encountered a similar issue where the solutions provided didn't quite work for me: Fetch, set-cookies and csrf Proper Django CSRF validation using fetch post request Even though I believe my post request content is correct, I still keep g ...

Having trouble accessing the 'checked' property of the checkbox

I've been developing a web application using Vite, JavaScript, jQuery, and Bootstrap. I'm facing an issue where the jQuery .is(':checked') function is not working as expected on one specific page. Despite the checkboxes being checked, t ...

Having trouble displaying PHP content above the footer section

Having a bit of an issue here. Everything on the page is printing out correctly, except for the PHP content. It keeps showing up at the bottom of the page below the footer. I need it to display above the footer. I've checked the code and it should be ...

Customize CSS in Razor/Sitecore

We are seeking a solution for our component that includes a background image, requiring it to be loaded through CSS. Our front-end developer prefers using background: url(/*path here*/).... The proposed solution involves retrieving the image path from Site ...

What is preventing my Button's onClick() method from being effective?

Below is a snippet of my HTML layout using the sciter framework: <div id="volume_micphone_slider" style="z-index:1;"> <input id="volume_slider" class="volume_slider" type="vslider" name="p1c" max="100" value="20" buddy="p1c-buddy" /> < ...

Mastering the flow of control in Node.js programs

Attempting to grasp control flow within Node.js applications. Specifically, does control loop back to the original function once the callback method completes, similar to a callback stack in recursive calls? A simple program was crafted to make a GET call ...

Organizing month and year in angularjs: A step-by-step guide

I have a table with a column for month and year. I need to sort the dates by year. Can someone please help me with this? You can view the code in the provided fiddle. In my case, the date format is "MMMM yyyy". For example, if I have "August 2016", "Septe ...

Is there a way to display the button solely when the cursor is hovering over the color?

When I hover over a particular color, I want the button to show up. However, instead of displaying the button only for that color, it appears for all the colors of the product. Also, the placement of the button on the left side means that if I try to hover ...

The Guide to Utilizing Autonomous Models in Directive

Hey there! I have a question regarding a radio button directive. In this directive, I pass a model for the collection that will be set to the selected radio button. var app = ChartsModules.getInstance().getModule("amkaiCharts.directives"); ...

Issue: TypeError - history.push function is not recognized. This problem occurs sporadically

There seems to be inconsistency with this error - it doesn't occur every time. At times the code works fine, while other times it gives errors. const dispatch = useDispatch() const userDetails = useSelector(state => state.userDetails) const { erro ...

What is the best method to handle errors when retrieving JSON data and updating it using fetch()?

I need to figure out a way for the setMessage not to appear when encountering a PUT ERROR 404 not found in the updateTemplate function. I attempted using catch(err) but was unsuccessful. Here is the complete code snippet: My unique version of the code... ...

Javascript Error: Missing Object (SelectedIndex Property)

Struggling to find a solution for the mysterious "Object Expected" error that keeps popping up. Currently working on a concert attendance form page where users input their information. The pesky error is showing up in my function "totalBill," specifically ...