Set height to the lowest height of the sibling child div
I have multiple rows, every row has multiple columns, in each column i have a div + a paragraphe, the div includes an image. i need to set the div with the class cover-bg to the lowest height of cover-bg in the same row the calculated height of the cover-bg in the first row can't be the same height in the second row
<div class="row">
<div class="col-md-4">
<div class="cover-bg"><img src="url"></div>
<p>text here</p>
</div>
<div class="col-md-6">
<div class="cover-bg"><img src="url"></div>
<p>text here</p>
</div>
</div>
<div class="row">
<div class="col-md-5">
<div class="cover-bg"><img src="url"></div>
<p>text here</p>
</div>
<div class="col-md-4">
<div class="cover-bg"><img src="url"></div>
<p>text here</p>
</div>
</div>
I have tried this but it sets the lowest height of all the rows :
var minHeight = Math.min.apply(null, $('.cover-bg').map(function(){return $(this).height()}));
$('.cover-bg').height(minHeight);
I am having trouble manipulating the siblings() and children()
The problem is how to separate and set the height for each row
Solution 1:
You'll need to set an image height for each row otherwise all will have the same height.
I got a bit confused with the suggested jquery so here is a snippet which spells it out in pure JS.
For each row it finds the minimum image height and then sets a CSS variable property of that row to that height. This is used to style each of the images in that particular row.
<!doctype html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/css/bootstrap.min.css">
<style>
.row {
margin-bottom: 20px;
}
.row .cover-bg img:first-child {
height: calc(var(--h) * 1px);
}
</style>
</head>
<body>
<div class="row">
<div class="col-md-4">
<div class="cover-bg"><img src="https://picsum.photos/id/1015/200/500"></div>
<p>
weofijae
<br/> weofjiawef awoeifj awoefij
</p>
</div>
<div class="col-md-6">
<div class="cover-bg"><img src="https://picsum.photos/id/1016/200/1000"></div>
<p>text here</p>
</div>
</div>
<div class="row">
<div class="col-md-5">
<div class="cover-bg"><img src="https://picsum.photos/id/1015/200/300"></div>
<p>text here</p>
</div>
<div class="col-md-4">
<div class="cover-bg"><img src="https://picsum.photos/id/1016/200/200"></div>
<p>text here</p>
</div>
</div>
<script>
function start() {
const rows = document.querySelectorAll('.row');
rows.forEach(row => {
const imgs = row.querySelectorAll('img');
let heights = [];
imgs.forEach(img => {
heights.push(img.height);
});
row.style.setProperty('--h', Math.min.apply(null, heights));
});
}
window.onload = start;
</script>
</body>
</html>
Note: you need to wait til the images are loaded before getting their natural heights.
Run the snippet full page otherwise the rows may wrap.