Dynamically Equalizing Card Headers Using CSS or jQuery
Problem:
Matching the heights of card headers that are not direct children of the parent container, despite changes in content and responsive screen sizes.
CSS Solution:
This approach leverages the inline-block property and automatic height adjustment features of HTML table cells to dynamically equalize header heights.
<table class="parent"> <thead> <tr> <th class="header">Header 1</th> <th class="header">Header 2</th> <th class="header">Header 3</th> </tr> </thead> <tbody> <tr> <td class="item"> <div class="content">Content for Header 1</div> </td> <td class="item"> <div class="content">Content for Header 2</div> </td> <td class="item"> <div class="content">Content for Header 3</div> </td> </tr> <tr> <td class="item"> <div class="content">Content for Header 1</div> </td> <td class="item"> <div class="content">Content for Header 2, with extra wrapping</div> </td> <td class="item"> <div class="content">Content for Header 3</div> </td> </tr> </tbody> </table>
.parent { display: table; } .header { display: inline-block; background-color: cornflowerblue; } .item { display: table-cell; padding: 20px; } .content { background-color: salmon; flex-grow: 1; }
jQuery Solution:
This solution employs jQuery to set equal heights for headers and can be customized based on row or column requirements.
<div class="row"> <div class="col item"> <div class="header">Header 1</div> <div class="content">Content for Header 1</div> </div> <div class="col item"> <div class="header">Header 2</div> <div class="content">Content for Header 2</div> </div> <div class="col item"> <div class="header">Header 3</div> <div class="content">Content for Header 3</div> </div> </div>
$(function() { // Preload header elements var $headers = $('.header'); // Set equal height on all headers function setEqualHeight() { var maxHeight = 0; $headers.each(function() { maxHeight = Math.max(maxHeight, $(this).outerHeight()); }); $headers.css('height', maxHeight + 'px'); } // Set equal height per row function setEqualHeightPerRow() { var previousTop = 0; var height = 0; $headers.each(function() { var currentTop = $(this).offset().top; if (currentTop > previousTop) { $(this).css('height', height + 'px'); previousTop = currentTop; height = 0; } height = Math.max(height, $(this).outerHeight()); }); $(this).css('height', height + 'px'); } // Run on load and resize setEqualHeight(); $(window).resize(setEqualHeight); });
These solutions provide dynamic and responsive matching of header heights, ensuring consistency in UI design regardless of content or screen size.
The above is the detailed content of How can I dynamically equalize the heights of card headers that are not direct children of their parent container using CSS or jQuery?. For more information, please follow other related articles on the PHP Chinese website!