Question

JSFiddle here

var element=$("#outer"); // element is a jQuery object
var max=0;
element.children().each(function(index, child) {
    child=$(child);
    var childPos=child.position();
    var childMax=childPos.top+child.outerHeight();
    if(childMax>max) {
        max=childMax;
    }
});
element.css({height: max+'px'});

can anyone please add border to #outer div without giving fix height ? :/

I try to use jquery but it won't work. Kindly provide me any working example if possible.

Was it helpful?

Solution

Seems like you're trying to put the border around the content in box2 which is actually overflowing (meaning it's height property won't reflect the height of it's content).

Change the CSS to be height:auto:

#box1, #box2 {
    width: 20px;
    height: auto;
    background: #f00;
}

Then change your selector for the each:

element.find('*').each( function(index, child) { 
    //... 
});

So you get the element box2 in the iteration because it's not a direct child of outer.

Working Fiddle

Update: Alternative Solution

If you want to keep your CSS as you originally wrote it, you can find the scrollHeight of the DOM element and use that to determine the height of the content inside of it in the case of an overflow.

Change this line:

var childMax=childPos.top+child.outerHeight();

To this:

var childMax=childPos.top+child[0].scrollHeight;

Alternative Solution Fiddle

OTHER TIPS

I added a border here:

#outer {
left: 50px;
top: 50px;
width: 200px;
background: #aaa;
border:1px solid red;
}

It now has border. what do you want to achieve? perhaps you want it to have a border, and to contain all of its child elements?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top