Search code examples
svgresponsive-designviewport

Make SVG cover entire viewport (responsive) and center SVG group object vertically and horizontally in viewport


I am trying to configure a SVG to responsively cover the entire viewport. I've been able to do this using css and svg attributes but this method makes it difficult to achieve my secondary requirement. Inside the SVG i would like to horizontally/vertically center a object.

--edit--

 <svg 
      version="1.1" 
      xmlns="http://www.w3.org/2000/svg" 
      xmlns:xlink="http://www.w3.org/1999/xlink" 
      x="0px" 
      y="0px"      
      style="position:absolute; top:0; left:0; z-index:100"
      width="100%" 
      height="100%">     
      <rect 
        ref="introWhiteRec"
        width="100%"
        height="100%"
        fill="white"                          
      />
      <rect 
        ref="introBlackRec"
        width="100%"
        height="100%"
        fill="black"         
      />
      <rect
          ref="introBlackRec"
          width="100"
          height="100"
          fill="grey"/> <!-- center this h and v? -->                
    </svg>

Solution

  • I'm not very sure if this is what you need:

    <svg 
          version="1.1" 
          xmlns="http://www.w3.org/2000/svg" 
          xmlns:xlink="http://www.w3.org/1999/xlink"      
          style="position:absolute; top:0; left:0; z-index:100"
          width="100%" 
          height="100%">     
          <rect 
            ref="introWhiteRec"
            width="100%"
            height="100%"
            fill="white"                          
          />
          <rect 
            ref="introBlackRec"
            width="100%"
            height="100%"
            fill="black"         
          />
          <rect 
              ref="introBlackRec"
              width="100"
              height="100"
              x="-50"
              y="-50"
              style="transform: translate(50vw, 50vh)";
              fill="grey"/> <!-- center this h and v? -->                
        </svg>