What is the best way to ensure uniform header height on cards or similar elements using flexbox?

Avoid using hacks

Do not hard code the solution. The goal is to create a solution that works for dynamic content and responsive screen sizes, rather than just one specific case.

The issue lies in the fact that the headers are not direct children of the elements they need to match heights with.

Find the codepen here:

https://codepen.io/anon/pen/OxzrzV

HTML

<h1>disclaimer: resize the window. Make the blue headers in a row match height</h1>
<div class="row mycontainer">
  <div class="col-12 col-md-4 col-lg-3">
    <div class="item">
       <div class="header">bippo</div>
        <div class="content">some content lala some content lala </div>
    </div>
  </div>
    <div class="col-12 col-md-4 col-lg-3">
    <div class="item">
       <div class="header">bippo</div>
        <div class="content">some content lala </div>
    </div>
  </div>
    <div class="col-12 col-md-4 col-lg-3">
      <div class="item">
       <div class="header">bippo</div>
        <div class="content">some content lala </div>
      </div>
  </div>
  <div class="col-12 col-md-4 col-lg-3">
    <div class="item">
       <div class="header">bippo</div>
        <div class="content">some content lala </div>
    </div>
  </div>
    <div class="col-12 col-md-4 col-lg-3">
    <div class="item">
       <div class="header">bippo</div>
        <div class="content">some content lala some content lala some content lala </div>
    </div>
  </div>
    <div class="col-12 col-md-4 col-lg-3">
      <div class="item">
       <div class="header">oh no this header wraps</div>
        <div class="content">some content lala </div>
      </div>
  </div>
</div>

CSS

 body{
  padding: 20px;
}

.item{
  height: 100%;
  padding-right: 20px;
  padding-top: 20px;
  display: flex;
  flex-direction: column
}

.header{
  background-color: cornflowerblue;
}

.content{
  background-color: salmon;
  flex-grow: 1;
}

.mycontainer{
  max-width: 500px;
}

What am I looking for?

I want the blue headers to always have the same size as all elements in the current row.

A reliable jQuery solution is acceptable, as long as it works seamlessly on resizing. A change in the HTML structure is also welcome if it ensures responsiveness.

Here is an example of what I want to achieve (without hard coding and being responsive):

https://i.sstatic.net/H1anS.png

Answer №1

There are two main approaches to achieve this desired effect: one using CSS and the other involving jQuery.

  • CSS - How to have children in different parents the same height?

The first method demonstrates how to set equal heights for all items, while the second method sets equal heights per row by checking each item's top value (which changes when a new row begins).

In addition, there are a couple of optimizations included such as preloading items and avoiding processing if there is only one item or column.


View Updated codepen 1

Snippet 1:

(function ($) {

  // preload object array to gain performance
  var $headers = $('.header')
  
  // run at resize
  $( window ).resize(function() {
    $.fn.setHeaderHeight(0);   
  });  

  $.fn.setHeaderHeight = function(height) {

    // reset to auto or else we can't check height
    $($headers).css({ 'height': 'auto' });
    
    // get highest value
    $($headers).each(function(i, obj) {    
      height = Math.max(height, $(obj).outerHeight())
    });

    // set the height
    $($headers).css({ 'height': height + 'px' });    
  }

  // run at load
  $.fn.setHeaderHeight(0);
  
}(jQuery));
body{
  padding: 20px;
}

.item{
  height: 100%;
  padding-right: 20px;
  padding-top: 20px;
  display: flex;
  flex-direction: column
}

.header{
  background-color: cornflowerblue;
}

.content{
  background-color: salmon;
  flex-grow: 1;
}

.mycontainer{
  max-width: 500px;
}
(pre and script elements continue...)


View Updated codepen 2

Snippet 2:

(paste snippet from here)

To cater to those who prefer plain javascript, I have also provided an updated sample that dynamically applies a class with computed height values to achieve equal heights on all items.

Stack Snippet:

(paste snippet from here)

Answer №2

My solution involves using jQuery to handle the task. The challenge here is to ensure that each row has equal height, regardless of the content in each row.

What I've implemented is a logic where I assign a unique class based on the top position of each header element. This makes it easy to identify and manipulate entire rows when needed. During iteration, I track the maximum height within each row and apply it to all elements in that row once a new row begins.

Below is the snippet of code showcasing this approach...

function adjustHeaderHeights() {

    // Reset all heights initially.
    $('div.header').css('height','auto');

    var curRow=$('div.header').first().offset().top,
        curRowMaxHeight=$('div.header').first().height();
    var n = $('div.header').length;

    $('div.header').each(function(index) {

        var rowId = $(this).offset().top;
        $(this).addClass('rowid'+rowId);

        if (rowId != curRow) {
            $('div.header.rowid'+curRow).height(curRowMaxHeight); 
            curRow = rowId;
            curRowMaxHeight=$(this).height();
        }
        else {
            curRowMaxHeight = $(this).height() > curRowMaxHeight ? $(this).height() : curRowMaxHeight;

            if (index+1 == n)
                $('div.header.rowid'+curRow).height(curRowMaxHeight);
        }
    });

}

$(window).resize(function() {
    adjustHeaderHeights();
});

adjustHeaderHeights();

I trust this solution will be beneficial for your needs.

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

"Placing the save button on top of a div - a step

I am trying to position a div with an ID below a save button in my HTML code. The current setup looks like this: <button id="item_new" data-action="create" class="floating-button mdl-button mdl-js-button mdl-button--fab mdl-js-ripple-effect mdl-button- ...

trouble with fetching data

Within my Backbone view, I have the following code snippet: var BookView = Backbone.View.extend({ initialize: function() { this.render(); }, render: function() { this.model.fetch({ success : function(model, resp, opt) { alert(this.$el. ...

The trick to keeping a div open without it closing until the page is refreshed

I am currently working on a project that involves creating an interactive map with dots. Each dot, when clicked, should trigger the display of a form related to that specific dot within a <div>. My challenge is ensuring that once a dot is clicked an ...

elements on the page that automatically update using AJAX

On my webpage, there is a news slider that displays items one by one. The page automatically refreshes to show new items. I am working on using ajax and a jquery timer to update the page whenever a new item is added. I'm trying to use AJAX to retriev ...

Using JQuery Noty in combination with Codeigniter Framework

I am currently attempting to implement a notification feature using JQuery, specifically with Noty in my CodeIgniter Project. Here is the script code I have used: <script type="text/javascript> $(document).ready(function() { <?php if (!empty($ ...

How can I ensure that the AppBar background color matches the color of the navigation bar?

Having trouble changing the background color of the <AppBar> in my project. Using the Container component to set a maximum screen size, but encountering issues when the screen exceeds this limit. The AppBar background color appears as expected while ...

Maintain the fixed position of the table header while scrolling

I am facing an issue with my table setup - I want the header to stay fixed while scrolling through the body. Here is how my table structure looks: <table> <thead> <tr> <th>Header 1</th> ...

Aligning elements in the center vertically using absolute positioning for multiple elements

I have been experimenting with a method to vertically center an element in a div that has unknown height. You can check out the approach I used here: In my case, I am working with anchor tags and this solution was particularly helpful due to the position ...

The functionality of switching between two layouts using a JavaScript button is currently not functioning

My concept involves implementing a switch that alternates between displaying a bootstrap carousel and cards. Essentially, one of them will be visible when the button is pressed while the other remains invisible. Initially, I am attempting to hide my existi ...

Displaying a hand cursor on a bar chart when hovered over in c3.js

When using pie charts in c3js, a hand cursor (pointer) is displayed by default when hovering over a pie slice. I am looking to achieve the same behavior for each bar in a bar chart. How can this be done? I attempted the CSS below, but it resulted in the h ...

Tips for preserving drop down selections when refreshing the page

I am currently working on a program with 2 drop-down menus and 2 buttons. My goal is to have the first button disabled and second enabled when both dropdowns are selected and the "start" button is clicked. Additionally, I want the dropdowns to be disabled ...

Display fixed or absolute elements within a scrollable container

I want to create a unique design with overlapping divs that can be selectively displayed through scrolling. While this effect is possible with images using background-attachment: fixed, I am seeking a solution that can work for any child element. Here is ...

Which library does stackoverflow utilize to showcase errors (utilizing Bootstrap popover for error help-block)?

Currently, I am using bootstrap's has-error and help-block classes to display validation error messages in my form. However, I find the error message display in Stackoverflow's Ask Questions Form to be very appealing. Are they using a specific js ...

Tips for making a website display in landscape mode rather than portrait orientation

As a newcomer to web design, I am curious if it is feasible to create a website that automatically rotates to landscape view when accessed on a mobile device. The current project I am working on is fluid in design, so this feature would greatly enhance t ...

Disabling directional focus navigation in CSS: A comprehensive guide

Is there a way to disable directional focus navigation properties, such as 'nav-up', 'nav-right', 'nav-down', 'nav-left', for elements on an HTML page? button { position:absolute } button#b1 { top:0; left:50%; ...

What causes the CSS height attribute to mess up UL lists?

I'm struggling to understand a problem in my nested list. When I set the height of LI elements, they end up overlapping each other. Can someone explain why this is happening and suggest a proper way to apply height without causing this overlap effect? ...

Using the Jquery .each loop is a powerful way to

I'm just getting started with jquery and I'm working on a .each loop that uses AJAX to fetch data and update list elements. Currently, the .each loop processes all list elements simultaneously... but what I really need is for it to process them o ...

Aligning elements next to each other in html / css without using any top margins

How can I arrange four blocks of text side-by-side, center them over a background image, and ensure they respond well on different screen sizes without using tables? I typically use tables for this layout, but I've heard that CSS/HTML5 can achieve th ...

fixed divs that remain in place while scrolling

In the past, I have implemented a method similar to this: However, I am not a fan of the "flicker" effect that occurs when the page is scrolled and the div needs to move along with it. Recently, I have come across websites where certain elements (such as ...

Hover activates a CSS animation where elements pop over other elements

I want to design a menu that resembles those "apps panels" we often see. My menu consists of 6 elements, arranged side-by-side with no space between them. When I hover over an element, it slightly pops as shown in the code snippet below: #account-bub ...