Setting equal heights for div's with jQuery
Answer to your specific question
Your code was checking all columns within any container, what you need to do is:
- Loop through each container
- Get the heights of each column within that container
- Find the highest one
- Apply that height to every column in that container before moving on to the next one.
Note: Try to provide an example jsfiddle of your issue, it enables us
to more easily help you and understand the issue, you get to see the
working solution straight away and it encourages quicker responses.
Quick (Rough) Example
$(document).ready(function(){
// Select and loop the container element of the elements you want to equalise $('.container').each(function(){ // Cache the highest var highestBox = 0; // Select and loop the elements you want to equalise $('.column', this).each(function(){ // If this box is higher than the cached highest then store it if($(this).height() > highestBox) { highestBox = $(this).height(); } }); // Set the height of all those children to whichever was highest $('.column',this).height(highestBox); });
});
.container { border 1px solid red; }.column { border: 1px solid blue; float:left; width: 30%; text-align:center; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container"> <div class="column">This is<br />the highest<br />column</div> <div class="column">One line</div> <div class="column">Two<br />lines</div></div><div class="container"> <div class="column">One line</div> <div class="column">Two<br>lines</div> <div class="column">One line</div></div>
Columns of equal height with jQuery
Update from 2022
JavaScript
jQuery is a bit overkill for something like this; you could use vanilla JavaScript:
// Construct a NodeList of all column elements
const columns = document.querySelectorAll(".column");
// Determine the tallest Node in the list based on its offsetHeight
const tallest = Math.max( ...[ ...columns ].map( c => c.offsetHeight ) );
// Apply that height to all Nodes in the NodeList
columns.forEach( column => column.style.height = `${tallest}px` );
Or (preferably) CSS
In reality, JavaScript probably shouldn't be used at all. Modern browsers have supported Flexbox for quite some time, which is capable of keeping laterally-placed elements equal in height:
Assuming the following (taken from original demo below):
<div class="container">
<div class="column">Foo</div>
<div class="column">Foo<br/>Foo<br/>Foo</div>
<div class="column">Foo</div>
</div>
Flexbox creates columns of equal-height (based on the tallest) with the following:
.container {
display: flex;
}
Original Answer
Cycle through each column, and find the tallest. Then set all to that height.
var maxHeight = 0;
$(".column").each(function(){
maxHeight = $(this).height() > maxHeight ? $(this).height() : maxHeight;
}).height(maxHeight);
Online Demo: http://jsbin.com/afupe/2/edit
Equal height columns using Bootstrap and jQuery
function equal_height() {
var map_height = $('#map-container').height();
var selection_height = $('#selection').height();
if (selection_height < map_height) {
$('#selection').css('min-height',map_height);
}
}
$(document).ready(function(){
equal_height();
});
$(window).resize(function(){
equal_height();
});
jQuery Equal Height Divs
Firstly, you are probably aware only one element should have any one id
attribute. So I have changed the selectors as if they were classes to classes below. Even though you may not give a care about W3C standards, browsers or JavaScript API, etc may rely on this behaviour and not work now or in the future.
$(document).ready(function () {
$('div.parentDiv > div').each(function() {
var $sameHeightChildren = $(this).find('.sameHeight');
var maxHeight = 0;
$sameHeightChildren.each(function() {
maxHeight = Math.max(maxHeight, $(this).outerHeight());
});
$sameHeightChildren.css({ height: maxHeight + 'px' });
});
});
Note: If you want them all to be the same height despite their parent div, this is what you want.
$(document).ready(function () {
var $sameHeightDivs = $('.sameHeight');
var maxHeight = 0;
$sameHeightDivs.each(function() {
maxHeight = Math.max(maxHeight, $(this).outerHeight());
});
$sameHeightDivs.css({ height: maxHeight + 'px' });
});
This will set them to all be the height of the tallest, per parent div element.
Also, this answer may show you some other options.
Note too that if the content inside changes again (perhaps via JavaScript), you will need to call this again, or put it in a setInterval()
which I do not recommend.
Equal height columns per row
CSS Solution:
You can set the parent div
to display: flex
. In this case the CSS will look like so:
.row {
display: flex;
}
Example: https://jsfiddle.net/koralarts/e50wonqz/
Javascript Solution:
In the Javascript solution, I looped through each of the rows
with the class equal
as opposed to looping through the columns
with said class.
This will make sure that our scope is within the row
instead of all columns
available.
function equalizeHeight(group) {
var maxHeight = 0;
group.each(function(index) {
var divHeight = $(this).height();
if(divHeight > maxHeight) {
maxHeight = divHeight;
}
});
group.css('height', maxHeight);
}
This function can be called like so:
$('.equal').each(function() {
equalizeHeight($(this).children('div'));
});
https://jsfiddle.net/koralarts/e50wonqz/4/
Equal height for all column on each row
Somthing like this: https://jsfiddle.net/g2eo4n38/4/ ?
function fixHeight() {
// 1. Find the tallest element
var tallest = 0
$(".blog-item").each(function() {
var height = $(this).height();
if (height > tallest) {
tallest = height;
}
});
// 2. Adjust the height of the elements
$(".blog-item").each(function() {
$(this).height(tallest);
});
}
fixHeight();
Another approach is using CSS grids, like this (then you don't have to use JS for styling, which is nice):
#grid { display: grid; grid-template-columns: 1fr 1fr 1fr; grid-gap: 15px;}
.blog-item{ background-color: #f6f7f7; border-radius: 3px; padding: 15px; margin-bottom: 30px;}.blog-item .subtitle-item { font-weight: bold; color: #ffbd1f;}.blog-item-title{ text-transform: uppercase; margin-bottom: 30px}.blog-item-title h3{color: #333;}.blog-item-title h3, .blog-item-title p {transition: 0.3s;}.blog-item-title a:hover h3, .blog-item-title a:hover p {opacity: 0.6;}.blog-item-body{margin-bottom: 15px;}
.blog-item-tags ul li{ border: 1px solid #dcdcdc; display: inline-block; font-size: 12px; margin-right: 5px; margin-bottom: 20px; padding: 5px 10px; transition: 0.3s; cursor: pointer;}.blog-item-tags ul li:hover{ background-color: #ffbd1f; color: #fff; border-color: #ffbd1f;}.blog-item a{ text-transform: uppercase; font-weight: bold; transition: 0.3s;}.blog-item a:hover {color: #ffbd1f;}.blog-item a .fa{ font-weight: bold; font-size: 16px; }.blog-item.featured{background-color: #ffbd1f;}.blog-item.featured .blog-item-title p, .blog-item.featured .blog-item-title h3, .blog-item.featured p, .blog-item.featured a { color: #fff !important;}.blog-item.featured ul li { color: #fff !important; background-color:#dda114; border-color: transparent;}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<div id="grid"> <div class="blog-item bg featured"> <div class="blog-item-title"> <a href="#" target="_blank"> <p class="subtitle-item mb-5">Market Outlook</p> <h3 class="m-0">4Q 2018 Off-Grid And Mini-Grid Market Outlook</h3> </a> </div> <div class="blog-item-body"> <p>Acquisitions, partnerships, and new technology capabilities dominated the microgrid news flow in the past few months. Project activity…</p> </div> <div class="blog-item-tags"> <ul> <li>Tag #1</li> <li>Tag #2</li> </ul> </div> <a href="content.html">Read more<i class="fa fa-angle-right ml-5" aria-hidden="true"></i></a> </div> <div class="blog-item"> <div class="blog-item-title"> <a href="#" target="_blank"> <p class="subtitle-item mb-5">Insight</p> <h3 class="m-0">Distributed Energy in Emerging Markets</h3> </a> </div> <div class="blog-item-body"> <p>Advances in distributed technologies at the frontiers of today’s energy system can now provide power where the traditional grid is…</p> </div> <div class="blog-item-tags"> <ul> <li>Tag #1</li> <li>Tag #2</li> <li>Tag #3</li> <li>Tag #4</li> <li>Tag #5</li> <li>Tag #6</li> </ul> </div> <a href="content.html">Read more<i class="fa fa-angle-right ml-5" aria-hidden="true"></i></a> </div> <div class="blog-item"> <div class="blog-item-title"> <a href="#" target="_blank"> <p class="subtitle-item mb-5">Insight</p> <h3 class="m-0">Clean Energy And The Paris Promises</h3> </a> </div> <div class="blog-item-body"> <p>The 2015 Paris Agreement saw virtually every nation on earth pledge to address the threat of climate change. Each country’s Nationally…</p> </div> <div class="blog-item-tags"> <ul> <li>Tag #1</li> <li>Tag #2</li> <li>Tag #3</li> <li>Tag #4</li> </ul> </div> <a href="content.html">Read more<i class="fa fa-angle-right ml-5" aria-hidden="true"></i></a> </div></div>
Equal heights per row
For examples sake Lets assume you are out putting your html via a php loop (if not then you can simply loop though the elems assigning a class) same principle applies.
PHP example outputting html
<?php foreach($array as $k => $v): ?>
<?php if($k % (4) == 0) $class++; ?>
<div class="row-num-<?php echo $class ?>">
// div content variable height
</div>
<?php endforeach; ?>
jQuery Setting Equal Height per row using your existing code
var totalFrames = $('div[class*=row-num-]').length;
for ( var i = 1, l = totalFrames; i < l; i++ ) {
var heights = $(".row-num-"+i).map(function() {
return $(this).height();
}).get(),
maxHeight = Math.max.apply(null, heights);
$(".row-num-"+i).height(maxHeight);
}
This assumes your row is 4 elems wide. You can set this or dynamically calc it depending on your use. In the jQuery we loop through all elems with a class like row-num-
then we target each one setting the height. These will have the same class every four elems. It continues until the current count of this class name has been reached.
DEMO https://jsfiddle.net/DTcHh/18026/
Related Topics
How to Add HTML Inside a Title Attribute
Phantomjs Page.Content Isn't Retrieving the Page Content
Passing Mouse Clicks Through an Overlaying Element <Div>
Change Iframe Src by Clicking a Link
JavaScript Loading Screen While Page Loads
Disable Zoom on Input Focus in Android Webpage
D3 Bar Graph Example Not Working Locally
How to Detect When a New Element Has Been Added to the Document in Jquery
Calculate Position of Selected Text JavaScript/Jquery
Canvas.Todataurl() Security Error the Operation Is Insecure
Specify Parent Divs Opacity But Make It Not Affect Children HTML Elements
Getelementbyclass().Setattribute Doesn't Work
Make a <Br> Instead of <Div></Div> by Pressing Enter on a Contenteditable
Why Doesn't JavaScript Newlines Work Inside HTML