Content

JQuery sets div height to “dynamic height” of another

I have two divs.

<div class="col-1"><p>Content</p></div> <div class="col-2"><img src="" alt="" /></div> 

With their respected content within everyone.

I am trying to set col-2 height exactly the same as col-1.

I tried this with jQuery:

  $(document).ready(function() { var divHeight = $('.col1').height(); $('.col2').css('min-height', divHeight+'px'); }); 

The problem is that col-1 has no height on it. It has a dynamic height that grows when its content grows. Therefore, the above code does not work for it.

Is it possible to set the minimum col-2 height equal to the dynamic height of col 1 using jQuery?

+5
source share
4 answers

this is great for me, just so that your class names are incorrect, class names must be .col-1 and .col-2 :

 $(document).ready(function() { var divHeight = $('.col-1').height(); $('.col-2').css('min-height', divHeight+'px'); }); 

Here is the fiddle

EDIT - based on comments:
You can do it all without using jquery

  • Flexbox (not supported in IE 8 and 9) - if you apply flex to the parent div, it will make all the heights of its children equal:

      .row{ display: flex;} 
  • table - you can specify a div in the table

     .row {display: table; } .row div { display: table-cell;} 
+4
source
 $('.col-2').css({'minHeight': divHeight+'px'}); 

you can put this in a callback. therefore, it is executed when the height changes. e.g. Detecting when div height changes using jQuery

0
source

Add a resize event listener when col-2 resizes col-2 function

 $(document).ready(function() { $('.tb-col1').resize(function(){ var divHeight = $('.col-2').height(); $('.col-2').css('minHeight', divHeight+'px'); } }); 
0
source

First of all, you need to fix the class names that missed the '-' in your jQuery code.

If you want to get a .col-1 height, you can do this in several ways, which I will discuss later.

Before that, in each case, you need to write a function that gives the height .col-1 and set .col-2.

 $(document).ready(function() { function set_heights(){ var divHeight = $('.col-1').height(); $('.col-2').css('min-height', divHeight+'px'); } }); 

Then you just call the function whenever you need ...

Some of the ways:

  • set the interval or timer to call the function above once for a certain period of time.

     setInterval(function(){ set_heights(); }, 100); 
  • use the resize event for .col-1. to call the function above when .col-1 has ever been modified.

     $('.col-1').resize(function(){ set_heights(); }); 
  • use bind

remember !!! for responsive design you also need to call the function above even when the window size is resized!

Good luck

0
source

All Articles