'How to reload a div for equal height child on window resize
I wrote a script to give equal height to child elements of wrapper. It is working fine on page load, but when I resize or change the orientation of my iPad, the height remains the same as it was during page load.
$(window).on('load resize', function () {
$('.equal-height-wrapper').each(function () {
var heightArray = [];
var allbox = $(this).find(".equal-height-box");
$(allbox).each(function () {
heightArray.push($(this).height());
});
var maxBoxHeight = Math.max.apply(Math, heightArray);
$(this).find('.equal-height-box').css('height', maxBoxHeight);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="equal-height-wrapper">
<div class="inner-wrapper">
<div class="equal-height-box">
</div>
<div class="equal-height-box">
</div>
</div>
</div>
I want to update the height of the child elements when they change. As of now, I've added overflow hidden so that any text that overlaps gets hidden.
I tried placing this script on load resize, but it doesn't make any difference.
Solution 1:[1]
Wrapped code in a named function so you can call it in various ways. I'd replace window .load
with $.ready
. Also added orientationchange
event. Then you get something like:
function setEqualHeight() {
$('.equal-height-wrapper').each(function() {
var heightArray = [];
var allbox = $(this).find(".equal-height-box");
$(allbox).each(function() {
$(this).height(""); // remove previously set heights
heightArray.push($(this).height());
});
var maxBoxHeight = Math.max.apply(Math, heightArray);
$(this).find('.equal-height-box').css('height', maxBoxHeight);
});
}
$(function() {
$(window).on('resize', setEqualHeight);
$(window).on('orientationchange', setEqualHeight);
setEqualHeight();
});
Solution 2:[2]
Why not using only CSS ? Something like this could work...
(Updated to work with FIXED container height, and unknown container height)
/* For fixed container HEIGHT */
.container-1 {
display: block;
width:150px;
background-color:yellow;
height:200px;
}
.child-1 {
width: 30px;
background-color: red;
display: inline-block;
vertical-align: top;
top:0px;
bottom:0px;
height:100%;
}
/* FOR UNKNOWN CONTAINER HEIGHT */
.container-2 {
display: table;
width:150px;
background-color:yellow;
}
.child-2 {
width: 30px;
background-color: red;
display: table-cell;
vertical-align: top;
}
Demo: http://jsfiddle.net/bkG5A/740/
You could also, consider using CSS FLEX
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |