Reputation: 737
I have been working on a site that I need equal columns for. I am using the following code:
<script type="text/javascript">
(function() {
function equalHeights(selector) {
var maxHeight = 0;
function calcEqualHeight() {
var el = $(this);
maxHeight = el.height() > maxHeight ? el.height() : maxHeight;
}
selector.each(calcEqualHeight).height(maxHeight);
}
equalHeights($('.exampleclass1'));
equalHeights($('.exampleclass2'));
})();
</script>
Trouble is, sometimes when the page loads, the heights don't always work correctly and content overlapped. I am wondering how I can change this to calculate the heights on page load?
Upvotes: 0
Views: 42
Reputation: 1497
i think you need to wrap selector with jQuery like this $(selector)
Please change this
selector.each(calcEqualHeight).height(maxHeight);
to this
return $(selector).each(calcEqualHeight).height(maxHeight);
also use return
and let me know if it doesn't work!
EDIT: CSS flex is a great solution, By just apply display: flex;
to parent it will make its child elements to have same height like below:
<style>
.parent{
display: flex;
}
</stlye>
<div class="parent">
<div class="chid"></div>
<div class="chid"></div>
</div>
Upvotes: 0
Reputation: 324640
Don't use JS to do CSS' job.
.column1 {background-color: #fcc}
.column2 {background-color: #cfc}
.columns {
display: flex;
align-items: stretch;
}
.columns>div {
flex: 1 0 0;
}
<div class="columns">
<div class="column1"><p>Short column</p></div>
<div class="column2">
<p>Tall column</p>
<p>Look at how tall I am!</p>
</div>
</div>
Upvotes: 2