可能重复:
CSS - 相等高度列?
我有3个div.
像这样:
<div class="features"></div>
<div class="features"></div>
<div class="features"></div>
Run Code Online (Sandbox Code Playgroud)
他们将充满文字.我不知道多少钱.问题是,它们都是平等的高度势在必行.
我如何使用jQuery(或CSS)找到最高的DIV并将其他两个设置为相同的高度,创建3个相等高度的DIV.
这可能吗?
gha*_*yes 188
你不能轻易地选择高度或在CSS中进行比较,但jQuery和一些迭代应该很容易解决这个问题.我们将循环遍历每个元素并跟踪最高元素,然后我们将再次循环并将每个元素的高度设置为最高(工作JSFiddle)的高度:
$(document).ready(function() {
var maxHeight = -1;
$('.features').each(function() {
maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
});
$('.features').each(function() {
$(this).height(maxHeight);
});
});
Run Code Online (Sandbox Code Playgroud)
[附录]
Sheriffderek 在响应式网格中为此解决方案制作了一个JSFiddle.谢谢!
[第2版]
这是一个使用函数式编程的清洁版:
$(document).ready(function() {
// Get an array of all element heights
var elementHeights = $('.features').map(function() {
return $(this).height();
}).get();
// Math.max takes a variable number of arguments
// `apply` is equivalent to passing each height as an argument
var maxHeight = Math.max.apply(null, elementHeights);
// Set each height to the max height
$('.features').height(maxHeight);
});
Run Code Online (Sandbox Code Playgroud)
[版本3 - sans jQuery]
这是一个不使用jQuery(使用JSFiddle)的更新版本:
var elements = document.getElementsByClassName('features');
var elementHeights = Array.prototype.map.call(elements, function(el) {
return el.clientHeight;
});
var maxHeight = Math.max.apply(null, elementHeights);
Array.prototype.forEach.call(elements, function(el) {
el.style.height = maxHeight + "px";
});
Run Code Online (Sandbox Code Playgroud)
(这里是ES6)