0

I want to set the height of each of the div's under to equal that div's width.

<div class="container-fluid">
    <div class="row box-row">
        <div class="col-xs-6 col-md-4 box-container"></div>
        <div class="col-xs-6 col-md-4 box-container"></div>
        <div class="col-xs-12 col-md-4 box-container"></div>
        <div class="col-xs-12 col-sm-6 col-md-4 box-container"></div>
    </div>
</div>

I have tried with $('.box-container').css('height', $('.box-container').width());, but that sets all the div's height to equal the first divs width.

Any suggestions?

allegutta
  • 5,626
  • 10
  • 38
  • 56

2 Answers2

1

You need to use .each since it is a list of items with different widths:

$('.box-container').each(function(){
       $(this).css('height', $(this).width() + 'px');
});
renakre
  • 8,001
  • 5
  • 46
  • 99
1

You could use the function parameter of jQuery height() method:

$('.box-container').height(function(){
    return $(this).width();
});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • With this approach, the page becomes sluggish (and the divs begin to flicker when I resize the window (I have a relatively fast PC)). I was hoping to get this done with the .css attribute as this seems to be smoother on the system...? – allegutta May 09 '15 at 12:04
  • 1
    @allegutta This is not relevant to `height()` vs `css()` method but sounds like just issue regarding responsive design using CSS rules as media queries. Now i guess your best bet is to use instead a CSS only approach, e.g: http://www.mademyday.de/css-height-equals-width-with-pure-css.html But you'd have better to provide a minimalistic sample in question itself replicating your issue – A. Wolff May 09 '15 at 12:07
  • Yes, you are right. Tried with the use of the .css attribute, and it didn't make the flickering any better (my assumptions were wrong). – allegutta May 09 '15 at 12:11