Creating equal height for two element children using CSS

As I construct a pricing table, I'm faced with the challenge of ensuring that the child elements within each row are of equal height. The website is built on WordPress and utilizes a page builder, resulting in the row fields being positioned differently. In essence, it does not have the structure of a traditional table, making it tricky to achieve uniform row heights.

I attempted to utilize the matchHeight library for this purpose, but encountered difficulties in applying it specifically to the child elements within each column.

For reference, here's a demo available on CodePen

$('.col > div').matchHeight();

Answer №1

Have you considered incorporating the CSS property min-height into the .col > div selector? You can achieve this by adding

min-height: calc(100% / var(--col-rows));
, where var(--col-rows) is a CSS variable set in your stylesheet using data from the DOM via JavaScript.

.col {
/* target the div within the .col in your scss */
> div {
    /* Using the --col-rows variable to calculate 
       the number of elements in each row so they occupy equal space */      
    min-height: calc(100% / var(--col-rows));

To dynamically set the CSS variable based on the number of rows, you can use JavaScript to extract the row count and insert that value into your :root declaration with setProperty().

document.documentElement.style.setProperty(`--col-rows`, maxNum);

The CSS :root element now includes:

:root {
  --col-rows: 0; /* This will be updated by JS to reflect
                    the number of rows in the DOM */
}

To determine the row count, you can:

// Select all .col elements
const columnRows = document.querySelectorAll('.col');
// Initialize an empty array to store row lengths
const lengthArr = [];
// Iterate over the rows and gather the length of each column's rows
columnRows.forEach(item => {
  let count = item.children.length;
  // Add each row's length to the array
  lengthArr.push(count);
});
// Find the maximum row count
const maxNum = Math.max(...lengthArr);
// Update the --col-rows CSS variable using the root HTML element
document.documentElement.style.setProperty(`--col-rows`, maxNum);

With these adjustments, the number of rows will be automatically calculated using JavaScript and applied to the .col > div min-height property in your CSS styling.

Answer №2

If you're looking for a solution, this example could be helpful:

Check out this link

The concept is to hide certain headers in 4 columns or on large screens, and display them in 2 columns or on smaller screens. Additionally, the cells are rearranged under the 2 columns to group gold/plat/diamond together.

In my usual approach, I use percentages like 25% and 50%, but due to borders affecting the widths, adjustments were made to achieve the desired layout. If this poses an issue, consider placing borders on inner div elements instead of the cells directly.

Since your requirements weren't entirely clear, this may not be perfect but should provide enough guidance to help you achieve the desired outcome.

html

<div class="wrapper">
        <div class="wrapper-inner">
            <div class="col">
              
                <div class="o1"># of virtual attendee tickets (to use as giveaways, remote staff, etc.)</div>
                <div class="o1">Gold</div>
                <div class="rs o2"># of virtual attendee tickets (to use as giveaways, remote staff, etc.)</div>
                <div class="o2">Platinum</div>
                <div class="rs o3"># of virtual attendee tickets (to use as giveaways, remote staff, etc.)</div>
                <div class="o3">Diamond</div>

                <!-- Additional content here -->
              
            </div>
        </div>
    </div>

css

body {
  font-family: "Inter";
}
.wrapper {
  min-height: 100vh;
  display: flex;
  align-items: center;
  &-inner {
    display: flex;
    max-width: 900px;
    margin: 0 auto;
  }
  .col {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    > div {
      padding: 20px 0;
      border: 1px solid #e1e1e1;
      flex: 1 0 auto;
      width: 21%;
    }
  }
}
@media screen and (min-width: 799px) {
  .wrapper {
    &-inner {
      > .col {
        > div {
          &.rs {
            display: none;
          }
        }
      }
    }
  }
}
@media screen and (max-width: 800px) {
  .wrapper {
    &-inner {
      > .col {
        > div {
          width: 48%;
          
          &.o1 {
            order: 1;
          }
          &.o2 {
            order: 2;
          }
          &.o3 {
            order: 3;
          }
        }
      }
    }
  }
}

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

Tips for incorporating a tooltip into a disabled selectpicker option

A selectpicker I have is filled with various languages, listed as `li` tags within a `ul` tag. You can see an example in the image provided below. https://i.stack.imgur.com/dsg66.png It's noticeable that the `+ Add Language` option in the selectpick ...

Is it possible to make radio buttons in each row of a grid mutually exclusive within their respective column using JqGrid?

Is there a way to design a grid with a unique column of radio buttons so that when a user clicks on this column in a specific row, only the radio button in that row is selected? This column will contain a vertical group of radio buttons. I am seeking a so ...

What is the reason for min-content not being compatible with auto-fill or auto-fit?

My confusion lies in the fact that this code snippet works: .grid { display: grid; grid-template-columns: repeat(4, min-content); } Whereas this one does not: .grid { display: grid; grid-template-columns: repeat(auto-fill, min-content); } I am ...

Repairing the base navigation interface and correcting the hyperlink to redirect to a different webpage

Can anyone assist with aligning my bottom navigation bar and fixing a link issue on both navigation bars? I've been struggling to center it. Do you think using padding could solve the problem? I've tried guessing the pixel count, but to no avail ...

Unable to implement CSS styles on the provided HTML code

I'm currently working on integrating evoPDF into my asp.net application. When I click on a part of the HTML file, I send that portion using AJAX. So far, everything is working well up to this point. However, when I try to use the following methods fro ...

Custom jQuery plugin does not trigger click event

I recently discovered JQuery and decided to incorporate a plugin I stumbled upon for flipping images. The plugin can be found here. After adding the JavaScript library to my asp.net project, I utilized the flipOut method specified in the plugin. <scri ...

What is the best way to incorporate keyboard shortcuts into carousel operations using jQuery?

The example can be found here. I want to be able to navigate through the images using the left and right arrows on my keyboard. How can I achieve this using jQuery or CSS? This is the structure of the HTML: <div id="slider-code"> <a cla ...

Distinguishing background colors depending on the browser's compatibility with CSS properties

I've successfully designed a polka dot background using pure CSS: .polka-gr{ background-image: radial-gradient(#FAFFB3 20%, transparent 0), radial-gradient(#F1C3CB 20%, transparent 0); background-size: 30px 30px; background-positio ...

Updating the CSS class for a particular text segment enclosed in a <p> or <span> element

My <p> tag is set to contain several lines of text with a specific CSS class, but I am looking to modify the text format within certain parts of the paragraph. In the past, I would achieve this using the <font> tag, however it seems that HTML5 ...

Creating a specific ng-init condition for introducing new elements into the scope

Using ng-repeat, I am generating a series of todo items within div elements. My goal is to automatically apply the "editing = true" styling to these newly created items and if possible, focus on them as well. <div class="item" ng-class="{'editing- ...

Encountering unexpected outputs from JSONify

How can I send the result of a Python function back to my JavaScript using AJAX? Currently, I am receiving this response, but I am expecting either "True" or "False." Here is my jQuery code: var test = $.getJSON("/chk_chn", { name: channel_name }); ...

Is there a way to verify if td:nth-child(3) meets or surpasses a certain percentage threshold?

Currently in the process of developing a web page that retrieves various data sets, including three separate tables. My goal is to examine whether the value within the 3rd td element in each TR is equal to or exceeds a certain percentage. How can I determ ...

What is the best way to exclude the "table" property from a button inside a row of a table?

I'm currently working with bootstrap and have implemented a table with the property "table" to create a light background for the data pulled from a database. The design looks great, except for when I try to insert a button in each row for editing purp ...

I am experiencing issues with md-no-focus-style not functioning correctly in my configuration

I have a button that triggers the opening of my navigation bar: https://i.sstatic.net/nMr0i.jpg When I click on it, a hitmarker appears: https://i.sstatic.net/OLQaE.jpg The issue is that even after clicking on a navigation item and transitioning to the ...

Position navbar contents at the top of the screen

As I delve into learning Bootstrap4, I have come across the following snippet of HTML code: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> ...

"Create a table with rows that automatically adjust to the same height, regardless

Is there a way to create a table where the height remains constant regardless of the number of rows added? For example: https://i.sstatic.net/zJNqD.png Even if rows are added, I want the height to stay consistent. I cannot use percentage since the numb ...

Retrieve the XML document and substitute any occurrences of ampersands "&" with the word "and" within it

The XML file is not being read by the browser due to the presence of ampersands represented as "&". To resolve this, I am looking to retrieve the XML file and replace all instances of "&" with "and". Is this achievable? Despite attempting to use t ...

Transform JSON data into a new object

I'm currently exploring methods to manipulate my JSON data and create a separate object with the modified information. Specifically, I am working with this JSON file: My goal is to transform [dataset][data] into the following format: [Date.UTC(2013 ...

Is there a way to make a button on a single div only affect that specific div

I have a PHP query that echoes a div for each row in the table. I want the div to slide up and then, when the user clicks the "read more" button, the div slides down. However, since it is echoed in a loop, all the divs have the same IDs and classes. I wo ...

Evolution of the material through a fresh new slide

Can someone assist me with an animation issue? I have a slideshow consisting of 4 images that are supposed to transition automatically after a set time interval. Upon initially loading the webpage, the animation works perfectly as intended. However, subs ...