Search code examples
csshtmlsvgresponsiveness

Center slice a responsive svg image on resize


I have been trying to center slice the responsive Svg image on resize.

I have used preserveAspectRatio="xMidYMax slice" to achieve the output but the image width doesn't retain the width my screen.

body{
  margin:0;padding:0;
}

.wrapper {
	position: relative;
	width: 100%; 
	min-width: 100%;
	vertical-align: middle; 
	margin: 0;
}


.bg-svg {
	display: inline-block;
	position: absolute; 
	top: 0; left: 0; 
	width: 100%;
}
<div class="wrapper">
   <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"  d="0px" y="0px"
     width="1920px" height="1080px" viewBox="0 0 1920 1080" preserveAspectRatio="xMidYMax slice" class="bg-svg">
  <rect fill="#DACFB9" width="1920" height="1080"/>
  <rect x="719" y="296" fill="#EF6544" stroke="#FFFFFF" stroke-miterlimit="10" width="482" height="482"/>
  <rect x="1438" y="296" fill="#AFFF84" stroke="#D3D2D2" stroke-miterlimit="10" width="482" height="482"/>
  <rect x="1" y="296" fill="#7AEEFF" stroke="#D3D2D2" stroke-miterlimit="10" width="482" height="482"/>
  <text transform="matrix(1 0 0 1 841 557)" font-family="'GothamBlack'" font-size="60">MIDDLE</text>
  </svg> 
</div>

I am trying to achieve output like this Codepen demo but i dont want to use a background image.


Solution

  • Your main problem was that your SVG needed to have:

    width="100%" height="100%"
    

    so that it fills the wrapper. There was some other unnecessary CSS as well.

    body{
      margin:0;
      padding:0;
    }
    
    .wrapper {
      width: 100%; 
      height: 100vh;
    }
    <div class="wrapper">
       <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="100%" height="100%"
         viewBox="0 0 1920 1080" preserveAspectRatio="xMidYMid slice" class="bg-svg">
      <rect fill="#DACFB9" width="1920" height="1080"/>
      <rect x="719" y="296" fill="#EF6544" stroke="#FFFFFF" stroke-miterlimit="10" width="482" height="482"/>
      <rect x="1438" y="296" fill="#AFFF84" stroke="#D3D2D2" stroke-miterlimit="10" width="482" height="482"/>
      <rect x="1" y="296" fill="#7AEEFF" stroke="#D3D2D2" stroke-miterlimit="10" width="482" height="482"/>
      <text transform="matrix(1 0 0 1 841 557)" font-family="'GothamBlack'" font-size="60">MIDDLE</text>
      </svg> 
    </div>