Home > Net >  Is it possible to match SVG height to parent so that it acts like background 'cover'?
Is it possible to match SVG height to parent so that it acts like background 'cover'?

Time:06-07

I have an SVG Pattern imported as a reacted component rendered inside a parent container. I want the pattern to act like background-image : 'cover' inside the parent container but I'm not sure how to go about it. Currently the height exceeds the container. It looks like this. enter image description here

I can't use the SVG as a background image because I need to change it's fill color dynamically, I also need to be able to be to switch out different SVG patterns so using it as data uri makes the code very long in the main react function (storing several svgs).

Currently my code looks like this :

import React, { useState } from "react";
import { ReactComponent as Strata1 } from "./StrataSVG/Strata_01.svg"
import './App.css';


function App() {
   const [color, setColorChosen] = useState("blue");
   
  return (
     <>
         <div id="container">
             <Strata1 className="pattern" style={{ color: color }}/>
         </div>
      </>
  );
}
export default App;

CSS

#container {
   width: 100vw;
   height: 50vh;
   background-color: yellow;
}

.pattern {
   width: 100%;
   height: auto;
}

CodePudding user response:

To achieve the equivalent to CSS' background-size: cover in an <svg>, add the following attribute.

<svg ... preserveAspectRatio="xMidYMid slice" ...>
   ...rest of SVG...
</svg>
  • Related