Search code examples
javascriptjqueryhtmlcssdimension

Fitting child div inside parent div


As usual I have a parent and child div. Dimensions of a child div is not fixed. On click event I want to change dimensions of a child div to fit perfectly inside a parent div.

Note: This is same as pdf viewer fit page feature

HTML:

<a href="javascript:void(0)">Click</a>

<div id="parent">
    <div id="child4" class="child"></div>
    <!-- Please check by commenting childs one by one
    <div id="child2" class="child"></div>
    <div id="child3" class="child"></div>
    <div id="child4" class="child"></div>
    -->
</div>

CSS:

#parent {width:200px; height:100px; margin:100px auto; border:1px solid #000; overflow:auto}
.child {margin:0; border:1px solid #000; background-color:maroon; opacity:0.5}

#child1 {width:100px; height:50px}
#child2 {width:400px; height:100px}
#child3 {width:100px; height:500px}
#child4 {width:400px; height:500px}

JQuery:

$(function(){
    // Fit block
    $("a").click(function(){
        //I want logic here to fit $(".child") div perfectly
        //inside $("#parent") div. After changes dimensions
        //of child should be in proportion to its original width/height.
        //if height is more
        //then it should get parents height and if width is more
        //than it should get parents width but there should be no
        //vertical or horizontal scroll

        $(".child").height($("#parent").height() - 20);
    });
});

Fiddle - http://jsfiddle.net/LaT3E/4/

Thanks in advance.


Solution

  • Similar to how CSS background-size:contain; works?

    Here is the solution:

    $(function(){
    
    var $child = $('.child'),     
        h = $child.height(),
        w = $child.width(),
        bw = $child.css('border-width').replace('px',''),
        parH = $('#parent').height(),
        parW = $('#parent').width(),
        car = w / h, 
        par = parW / parH,
        newH,
        newW;
    
    $('a').click(function(){
        if(car > par){
            newW = parW;
            newH = h / w * newW;    
        }else{
             newH = parH;
             newW = w / h * newH;
        }
    
        $child.width(newW-bw*2);
        $child.height(newH-bw*2);
    
        console.log(w+'X'+h+' to '+newW+'X'+newH)
    });
    });
    

    Check this jsfiddle.