In web development, aligning elements vertically for an aesthetically pleasing and consistent layout is crucial. This question addresses the challenge of making multiple div elements of equal height, even when they contain varying amounts of content.
jQuery, a popular JavaScript library, provides a straightforward approach to identify the tallest element and set the height of others to match it:
$(document).ready(function() { var maxHeight = 0; // Initialize maxHeight to 0 $('.features').each(function() { // Loop through each .features div if ($(this).outerHeight() > maxHeight) { // Compare the current div's height to maxHeight maxHeight = $(this).outerHeight(); // Update maxHeight if the current div is taller } }); $('.features').each(function() { // Loop through each .features div again $(this).height(maxHeight); // Set the height of each div to maxHeight }); });
This script calculates the tallest div's height and assigns it to all the divs with the ".features" class, resulting in equal heights.
While CSS lacks direct height selection or comparison capabilities, a workaround using CSS Grid is possible:
.features-container { display: grid; grid-template-columns: repeat(auto-fit, minmax(initial, 1fr)); align-items: stretch; } .features { height: 100%; }
The above is the detailed content of How to Make Multiple Div Elements Equal Height Using jQuery or CSS?. For more information, please follow other related articles on the PHP Chinese website!