Search code examples
svgresponsiveviewport

Center SVG Object on responsive canvas


The SVG canvas is configured to adjust to the browser window and always fill 100% horizontally and vertically. I want the blue cube to always be in the bottom center of the window and also stay the same size.

Is there any way to change the position of the cube or the viewBox, so that the cube always stays in the bottom center no matter what size the browser window has?

Thank you in advance for your help.

<!DOCTYPE html>
<html>
<head>           
  <style type="text/css" media="screen">
    body { background:#eee; margin:0 }
    svg {display:block; position:absolute; width:100%; height:100%; background:#fff;}
  </style>
</head>
        
<body>
  <svg xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%">
    <rect x="0" y="0" width="100%" height="100%" fill="lightgreen"/> <!--Background--> 
    <rect x="0" y="0" width="100" height="100" fill="blue"/> <!--Cube-->
  </svg>       
</body>
</html>


Solution

  • I would use javascript for this. The clientWidth and clientHeight will give you the size of the SVG canvas.Alternatively you may use the getBoundingClientRect()

    let x,y;
    
    function init(){
    x = svg.clientWidth/2 - 50;
    y = svg.clientHeight - 100;
    therect.setAttributeNS(null,"x",x)
    therect.setAttributeNS(null,"y",y)
    }
    
    setTimeout(function() {
    		init();
    		addEventListener('resize', init, false);
    }, 15);
    body { background:#eee; margin:0 }
    svg {display:block; position:absolute; width:100%; height:100%; background:#fff;}
    <svg id="svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%">
        <rect x="0" y="0" width="100%" height="100%" fill="lightgreen"/><!--Background--> 
        <rect id="therect" x="50%" y="100%" width="100" height="100" fill="blue"/><!--Cube-->
      </svg>