I have a UI which has 4 components in a row, with multiple rows, and the height of each component is variable based on content inside of it.
I would like for each component in the same row to have the same height, for that height to be set by the tallest component in the row, and for each row to be independent from every other row in terms of setting heights for the components within it.
The place where I am currently stuck is that if I don’t break the loop, every component will take the height of the tallest component on the page, but if I break it at index < 4
then every component will take the height of the tallest component in the first row.
var maxComponentHeight = -1;
$('.component').each(function() {
var componentHeight = $(this).outerHeight();
if ($(this).index() < 4) {
if (componentHeight > maxComponentHeight) {
maxComponentHeight = componentHeight;
}
} else {
return false
}
})
$('.button button').on('click', function() {
$('.component').css('height', maxComponentHeight);
})
.button {
padding: 25px;
text-align: center;
}
.component {
background-color: gray;
border: 2px solid white;
color: white;
font-family: helvetica;
text-align: center;
height: 100px;
}
.component:nth-child(2) {
height: 200px;
}
.component:nth-child(7) {
height: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
<div class='button'>
<button>
align heights
</button>
</div>
<div class="row">
<div class="col-3 component">
component
</div>
<div class="col-3 component">
component
</div>
<div class="col-3 component">
component
</div>
<div class="col-3 component">
component
</div>
<div class="col-3 component">
component
</div>
<div class="col-3 component">
component
</div>
<div class="col-3 component">
component
</div>
<div class="col-3 component">
component
</div>
</div>
3
Answers
Is there any particular reason you want to use javascript to calculate the height instead of css?
Here’s some sample code which uses flex-box layouts to fill the space provided which sounds like what you wanted. Grid is also another good option if you want a fixed number of columns.
I prefer recalculating the desired heights inside a function after the button is clicked so I can set height for every 4 element not a preset height for all elements:
all you need to collect the max height in each row then after you click you assign the new heights.