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

Optimizing AngularJS performance with REST service caching

My AngularJS application requires caching of REST service responses, and I've come across libraries like angular-cached-resource that store data in the local browser storage. However, there are times when certain cached responses need to be deleted d ...

After running my CSS through the validator at http://www.css-validator.org/validator, I encountered a Parse Error. Any suggestions on how I can resolve this issue?

Here are the CSS codes for my media query section. @media (min-width:320px) and (max-width:575px){ .chakra{ width: 100%; float: unset; margin: auto; } } ...

Utilizing Angular to convert a string array into an array of enum values through an HTTP GET request

I have a list of different user roles defined in my typescript code: enum UserRole { CONSULTANT, MANAGER, ... } There is a REST endpoint /users/id/roles that returns an array of strings representing the roles of a specific user: [ "CONSU ...

Achieving a seamless blend of parent background with child background: A step-by

I am trying to make the parent background color overlap the child background color in two divs. Currently, the child's background is overlapping the parent's background. Please refer to the JS-Fiddle link below for more information: <div id=" ...

Issues with using hooks in a remote module in Webpack 5 module federation

I am attempting to create a dynamic system at runtime using Module Federation, a feature in webpack 5. Everything seems to be working well, but I encounter a multitude of 'invalid rule of hooks' errors when I add hooks to the 'producer' ...

What is the best way to pause function execution until a user action is completed within a separate Modal?

I'm currently working on a drink tracking application. Users have the ability to add drinks, but there is also a drink limit feature in place to alert them when they reach their set limit. A modal will pop up with options to cancel or continue adding ...

Error: Unable to instantiate a THREE.Scene object in Three.js due to TypeError

Recently, I decided to experiment with Three.js in order to incorporate it into a project of mine. However, upon running the initial example provided in the documentation: <html> <head> <title>My first Three.js app</title& ...

Conceal the scrollbar track while displaying the scrollbar thumb

Hey there! I'm looking to customize my scroll bar to have a hidden track like this. Everyone's got their own style, right? ::-webkit-scrollbar{ width: 15px; height: 40px; } ::-webkit-scrollbar-thumb{ background-color: #DBDBDB; borde ...

Using node.js to send a response with response.writeHead on the http module

While working on my own custom http module, I stumbled upon a few confusing points while studying the official node.js http module api: When a user utilizes the response.writeHead(statusCode, [reasonPhrase], [headers]) function, are the headers suppose ...

Confirm the input validity using jQuery for radio buttons, checkboxes, and dropdown menus

When it comes to validating input fields like text, email, radio, checkbox, and select, I have the following structure in my form: <fieldset> <div class="form-top"> <div class="form-bottom"> <div class="for ...

Redirecting script upon successful connection detection

I have created a script that checks for internet connectivity using an image, and redirects if internet is available. However, the issue is that it caches the images, leading to attempts to load them even when offline. Is there a different approach I can ...

Maintain the state of the previous page in Vue to ensure continuity

Currently in the process of creating a small PWA to simulate an Android app, I have discovered Vuejs. However, I encountered an issue that has proven difficult to resolve. While scrolling through lists on the homepage for movies, TV shows, or news, clicki ...

Is it possible to determine whether a path leads to a directory or a file?

Is it possible to distinguish between a file and a directory in a given path? I need to log the directory and file separately, and then convert them into a JSON object. const testFolder = './data/'; fs.readdir(testFolder, (err, files) => { ...

The jQuery Bootstrap Toggle is throwing an error: "Syntax error, unrecognized expression: #" within the Function.Sizzle.error

I am currently utilizing Jquery 3.3.1 and Bootstrap 3.3.7 that I fetched through npm. Below is the code snippet I have to toggle a div: <div class="text-right"> <a class="js-accordion-trigger" data-toggle="collapse" href="#advanced-search" ...

Is there a way to upload images using jQuery Ajax with a Grails webservice?

I am trying to upload files to a webservice that is implemented using GRAILS. Normally, I can consume this web service using CURL with the following command: curl -X POST -H "Authorization: 53676c55f8014c5eb84624b49d9c9e74" -H "Content-Type: multipart/for ...

Accessing a text document from a specific folder

As a novice in the world of HTML and PHP, I am attempting to develop a script that can access a directory, display all text files within it, allow for editing each file, and save any changes made (all operations will be managed through an HTML form). Howev ...

Getting the value of radio button groups in C# - A complete guide

Here is the HTML code: <form runat="server"> <table> <tr> <td> From Date: </td> <td> <input type="text" runat="ser ...

Show the checked options retrieved from controller

I am facing an issue with displaying certain checkbox values from the controller. In order to properly save these values, I believe it would be best to declare them in the controller and then use them in the HTML. However, my current code is not successful ...

Assign the physics settings to a variable within the A-frame

Exploring A-frame () for my scene creation has been exciting. I am curious about how I can dynamically adjust the physics in my virtual world using the A-frame physics component. The goal is to have the physics within my scene be determined by a variable c ...

Include a name in the set_values function using Rvest

I'm currently working on scraping data from this website. I have a code written in rvest for login, but each time the page refreshes, the form name changes. library(rvest) loginpage <- "https://demo.glpi-project.org/" pagesession <- html_sess ...