简体   繁体   中英

Each div get height of parent - jQuery approach

I have this structure:

<div class="container" style="height:(variable height)">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</div>
<div class="container" style="height:(variable height)">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</div>
<div class="container" style="height:(variable height)">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</div>

So I need each .box gets the height of the parent .container which has different heights from the other and it varies.

I need ONLY jQuery approach, no CSS cause I don't want to use absolute position, table-cell or whatever to do that.

Thanks!

You can use the function overload of .height

$('.box').height(function(){
    return $(this).parent().height();
});

If you really must use jQuery:

$('.container').each(function(){
    $(this).children().height($(this).height);
});

JS Fiddle demo .

It's worth noting, though, that if height is set on the .container elements then you could simply assign:

.box {
    height: 100%;
}

JS Fiddle demo .

No special position , or display , properties are required.

Incidentally, for a plain JavaScript sollution:

[].forEach.call(document.querySelectorAll('.container'), function (c) {
    [].forEach.call(c.children, function (b) {
        b.style.height = c.style.height;
    });
});

JS Fiddle demo .

References:

$(function(){
  $('.container').each(function(i,e){
    $(this).find('.box').css('height',$(this).height())
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM