Adjust the height to match the shortest sibling child div height

In my layout, I have multiple rows with each row containing multiple columns. Within each column, there is a div and a paragraph - the div contains an image. My goal is to set the div with the class cover-bg to the lowest height of cover-bg in the same row. It's important that the calculated height of the cover-bg in one row should not be the same as the height in another 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've attempted to use jQuery to set the lowest height for all rows but it doesn't work as expected:

var minHeight = Math.min.apply(null, $('.cover-bg').map(function(){return $(this).height()}));
$('.cover-bg').height(minHeight);

I'm struggling with manipulating the siblings() and children() methods

The main issue is how to differentiate and set the height for each individual row

https://i.stack.imgur.com/tvu3M.jpg

Answer №1

It is important to specify individual image heights for each row in order to avoid uniform height across all rows.

If you're finding the suggested jQuery solution confusing, here's a clear example using pure JavaScript instead.

The script calculates the minimum image height for each row and then assigns that value as a CSS variable to ensure proper styling of images within that 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>

Please note that it's crucial to wait until the images are fully loaded before retrieving their natural heights.

To view the snippet correctly, run it full page to prevent wrapping issues with the rows.

Answer №2

Give this a shot:

const smallestHeight = Math.min(...$.map($('.cover-bg'), (element) => ($(element).height())));
$('.cover-bg').height(smallestHeight);

Check out the demo here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

create a gentle appearance for an element

I am looking to replicate the visual appearance of each page on this particular website: There is something about the lighting that I really admire. I have attempted to recreate the animation, but I have been unsuccessful in my attempts. Any assistance wo ...

Refresh MySQL database using AJAX

In my form, there are both a submit button and a close button. When a user enters information and clicks the submit button, an answer is posted and saved in the database. If the user chooses to click the close button instead, the entry in the database will ...

Ways to retrieve row and column data from a datagrid

Below is the code snippet I am currently working with: import React from 'react' import Button from '@material-ui/core/Button'; import Checkbox from '@material-ui/core/Checkbox'; import { DataGrid } from '@material-ui/da ...

Trouble with Bootstrap Modal not closing properly in Chrome and Safari

ISSUE: I'm facing a problem where clicking on the X (font awesome icon) doesn't close the modal popup as expected. LIMITED FUNCTIONALITY ON CERTAIN BROWSERS: Currently, the X button for closing the modal works only in IE and Firefox. However, i ...

Troubleshooting CSS Animation Failure in Internet Explorer 11

My mouse over / mouse out animation works perfectly in Firefox and Chrome, but it's not functioning in IE. Can anyone suggest why this might be happening when it was working fine before? var actual = 1; var over = 0; var over2 = 0; function scrol ...

Deactivate "When the viewModel attribute holds the phrase 'some text'"

I came across this answer on Stack Overflow regarding checking for a value in Knockout, but it seems to be outdated. I am attempting to achieve something like this: <li> <span data-bind="text: Subject"></span> <!-- ko if: Subjec ...

Pinterest Style Card Layout using React-Semantic-UI

Utilizing semantic-ui-react in React, I am working on displaying cards with varying heights based on the amount of text. I am aiming for a pinterest style layout where each card's height adjusts according to the content it contains. .... <Card.Co ...

Utilize the converse.js plugin to set up a secure room with password protection

I'm looking to set up a password-protected room. Currently, I can create a public room and add a password in the configuration settings. However, I have to start by creating an unsecured, public room first. Is there a way to create a room with a pas ...

Regularly updating a book's interactive pages with turn.js technology

I experimented with generating dynamic content in turn.js using the sample provided here. This is an excerpt of the code I have written: <body> <div id="paper"> </div> </body> <script type="text/javascript"> $(win ...

"Techniques for incorporating a screen in Angular application (Switching between Edit and View modes) upon user interaction

We are currently working on a screen that requires the following development: This screen will have the following features: When clicking on a button, the fields should become editable. In the image provided, there is some repeated data, but in our case, ...

I am looking for guidance on removing the bottom line from the ionic 4 segment indicator. Any advice or tips on

.segment-button-indicator { -ms-flex-item-align: end; align-self: flex-end; width: 100%; height: 2px; background-color: var(--indicator-color); opacity: 1; } I am a beginner in hybrid app development and ...

Toggle the visibility of HTML elements by utilizing a JavaScript checkbox event

I have put together these JavaScript functions to hide the delivery address fields on my shopping cart address form if the goods are being sent to the billing address. The functions control the visibility of the HTML wrapped by... function getItem(id) { ...

Issue encountered when attempting to select a button with selenium

I'm attempting to use Selenium to click on a button, but encountering an error in the process. The specific error message is shown below: https://i.stack.imgur.com/NQjnh.png This snippet of code represents the accessed HTML page: https://i.stack.i ...

Looking for a list of events in Express.js?

I've been searching through the official documentation, but I couldn't find a list of events for express. Does anyone know if there's something like 'route-matched' so that I can use app.on('route-matched', () => {})? ...

"Designing with Vue.js for a seamless and adaptive user experience

I'm looking to customize the display of my data in Vuejs by arranging each property vertically. Instead of appearing on the same line, I want every item in conversationHistory to be displayed vertically. How can I achieve this in Vuejs? Can anyone off ...

What methods can Ajax utilize to make asynchronous requests and receive synchronous responses?

While using jQuery ajax to send a request to a web service, I came across an interesting bug: var AjaxResult; login = function () { AjaxResult = ""; $.ajax({ type: "POST", url: KnutBase.getServiceUrl() + "ServiceInterface/HmsPlanne ...

How to eliminate all <style> tags across the board using Regex in JavaScript

Is there a way to utilize regex in JavaScript for removing all instances of <style>, <style type="text/css">, </style>, and <style type="text/css"/>? I want the outcome to only present the CSS without any style tags. The code below ...

The Laravel href link will fail to work when the URL does not include the string 'http'

I am encountering an issue with a particular hyperlink tag <a href="{{ $organization->website }}">Link</a> When the URL in $organization->website does not start with http:// or https://, the link fails to direct me properly. Instead, it r ...

Issues with functionality of React/NextJS audio player buttons arise following implementation of a state

I am currently customizing an Audio Player component in a NextJs application using the ReactAudioPlayer package. However, the standard Import Next/Audio and using just <Audio> without props did not yield the expected results. The player functions as ...

Loading Webfonts Asynchronously in NextJS Using Webfontloader

I am currently working on a NextJS app where I am using webfontloader to load fonts dynamically. function load() { const WebFont = require("webfontloader"); WebFont.load({ google: { families: fonts } }); } However, I ha ...