Search code examples
javascriptcss

CSS Make parent div not fit children size


I have the following HTML :

   <div class="AnimationParent">                               
    <canvas id="canvas" width="534" height="554"></canvas>
  </div>

I'm setting the size of the canvas item using javascript in order to avoid scale issues in my animation... :

   $(window).resize(function() {
                RefreshCanvasSize();                                                        
                SetLayout();
            });               

   function RefreshCanvasSize() {
            var ParentWidth, ParentHeight;

            ParentWidth = $(".AnimationParent").width();
            ParentHeight = $(".AnimationParent").height();

            $("#canvas").prop('width', ParentWidth);
            $("#canvas").prop('height', ParentHeight);                                      
   }

The following code works when I'm expanding a page but not when it's shrinking. The parent div (AnimationParent) doesn't shrink.

here is the CSS for AnimationParent :

 width:100%;
 overflow:hidden;

can anyone help please ?

Regards,


Solution

  • Seems to be working fine. Can you provide a fiddle explaining the problem?

    Observation: note that as soon as you run it the first time, the canvas has a fixed size, and only resizes once the browser is resized. To make it always fit the parent, you need to call RefreshCanvasSize() on $(document).ready(...) as well.

    $(window).resize(function() {
      RefreshCanvasSize();                                                        
      //SetLayout();
    });               
    
    function RefreshCanvasSize() {
      var ParentWidth, ParentHeight;
    
      ParentWidth = $(".AnimationParent").width();
      ParentHeight = $(".AnimationParent").height();
    
      $("#canvas").prop('width', ParentWidth);
      $("#canvas").prop('height', ParentHeight);
      console.log($("#canvas").prop('width'), $("#canvas").prop('height'))
    }
    canvas {
      background: red;
    }
    .AnimationParent {
      background: blue;
      width: 100%;
      overflow:hidden;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="AnimationParent">                               
      <canvas id="canvas" width="534" height="554"></canvas>
    </div>