This question already has an answer here:
这个问题在这里已有答案:
- Maintain the aspect ratio of a div with CSS 22 answers
使用CSS 22答案保持div的宽高比
I want to set the height of each of the div's under to equal that div's width.
我想将每个div的高度设置为等于div的宽度。
<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.
我尝试过$('。box-container')。css('height',$('。box-container')。width());,但是将所有div的高度设置为等于第一个divs宽度。
Any suggestions?
2 个解决方案
#1
You could use the function parameter of jQuery height()
method:
你可以使用jQuery height()方法的函数参数:
$('.box-container').height(function(){
return $(this).width();
});
#2
You need to use .each
since it is a list of items with different widths:
您需要使用.each,因为它是具有不同宽度的项目列表:
$('.box-container').each(function(){
$(this).css('height', $(this).width() + 'px');
});
#1
You could use the function parameter of jQuery height()
method:
你可以使用jQuery height()方法的函数参数:
$('.box-container').height(function(){
return $(this).width();
});
#2
You need to use .each
since it is a list of items with different widths:
您需要使用.each,因为它是具有不同宽度的项目列表:
$('.box-container').each(function(){
$(this).css('height', $(this).width() + 'px');
});