我同意 hot_barbara,如果您需要支持任何旧版 IE 浏览器,那么 flexbox 很遗憾不是一个选项。有很多只使用 css 的解决方案,但是很多他们假设你有单行元素/网格项。
我已经用 jQuery 编写了自己的 javascript 解决方案,完整文章在这里:https://www.tenpixelsleft.com/responsive-equal-height-grid-columns/
这个想法是,您可以向函数传递一个选择器,该选择器以给定集合中的所有网格元素为目标,然后它将根据集合中的最高元素保持所有网格元素的相同高度。
/* ==================================================== *
* @param elementGroup - a group of dom objects to be iterated over and aligned
* @param offset - (int) offset number to be added to the height
* @param afterAlignment - callback function
* ==================================================== */
setElementGroupHeight = function(elementGroup, offset, afterAlignment) {
var offset = typeof offset !== 'undefined' ? offset : 0;
var tallestHeight = 0;
var elHeight = 0;
$.each(elementGroup, function() {
// Since this function is called every time the page is resized, we need to reset the height
// so each container can return to its natural size before being measured.
$(this).css('height', 'auto');
elHeight = $(this).outerHeight() + offset;
if (elHeight > tallestHeight) {
tallestHeight = elHeight;
}
});
// Set the height of all elementGroup elements to the tallest height
elementGroup.css('height', Math.ceil(tallestHeight));
// Callback
if (afterAlignment && typeof(afterAlignment) === "function") {
afterAlignment();
}
}
然后这样称呼它:
jQuery(function($) {
// Initialise on page load
var postGrid = $('.post-grid .js-align-col');
if (postGrid.length) {
setElementGroupHeight(postGrid);
$(window).on('resize', function(e, resizeEvent) {
// Realign on resize
setElementGroupHeight(postGrid);
});
}
});
在图像和字体加载竞争条件方面可能存在一些问题,这可能会导致初始高度计算出现偏差。上面的文章链接详细说明了如何最好地处理这些问题。