Mariyan
Mariyan

Reputation: 664

Resize divs related to parent divs with jQuery

So I have 4 divs. I want to change the size of the inner divs compared to parent divs. I want to dynamically change the child div size related to parent's one. Now I've added .top class, but I don't really know if its needed or if it will be useful.

Here is the fiddle I'm testing with http://jsfiddle.net/y3597/171/

jQuery below

$(".top").each(function () {
    $('.object').width($(".inner").parent().width());
});

CSS below:

.container1 { width: 200px; background: red; padding: 2px; }
.container2 { width: 225px; background: purple; padding: 2px; }
.container3 { width: 250px; background: blue; padding: 2px; }
.container4 { width: 275px; background: black; padding: 2px; }

/* top ? */

.inner { width: 150px; background: gray; }
.object { width: 100px; background: green; }

HTML below:

<div class="container1 top">
<div class="inner">
    <div class="object">Text 1</div>
</div>

<div class="container2 top">
<div class="inner">
    <div class="object">Text 2</div>
</div>

<div class="container3 top">
<div class="inner">
    <div class="object">Text 3</div>
</div>

<div class="container4 top">
<div class="inner">
    <div class="object">Text 4</div>
</div>

Upvotes: 0

Views: 65

Answers (1)

Artur Czyżewski
Artur Czyżewski

Reputation: 833

I think that you are trying to achieve this:

$(".top").each(function () {
    $(this).find(".object").width($(this).width()); 
});

In your code jQuery will check for every element with .object class in DOM on each loop. When you use (this) you are refering to element that is currently "selected" in loop.

Better way to achive this is to set widths od children to 100%, so they will inherit the witdhs from parents.

Upvotes: 2

Related Questions