简体   繁体   中英

Styling SVG as a React Component

Following the create-react-app doc, I imported a svg as a react component .

However, I can't seem to resize or position it properly, whether it's inline or through css.

I want to scale the SVG component to the same size as my other icon of 100px by 100px, then position at the bottom center of the screen.

I tried setting a width and height props for the svg component.

<IconClose
  className="bubbleBin"
  alt="close bubble"
  height="100px"
  width="100px"
  // viewBox="0 0 100 100"
/>

and in css.

.bubbleBin {
  display: flex;
  position: absolute;
  pointer-events: none;
  align-items: center;
  align-self: center;
  justify-content: flex-end;
}

Here's the minimal code to reproduce it. Full code in Sandbox if needed.

...
import { ReactComponent as IconClose } from './assets/icon_close.svg';

function App() {
  const ICON_WIDTH = 100;
  const ICON_HEIGHT = 100;

  return (
    <div style={{ display: 'flex' }}>
       <img
         src={require('./assets/cat_icon.png')}
         width={String(ICON_WIDTH)}
         height={String(ICON_HEIGHT)}
         alt="cat icon"
         draggable={false}
       />
      <IconClose
        className="bubbleBin"
        alt="close bubble"
        height="100px"
        width="100px"
      />
    </div>
  );
}

I expect the svg to be the same size as my cat icon but this is the result instead.反应中的svg样式问题

Thank you.

The viewBox of your SVG just has extra space around it. I quickly eyeballed a new viewbox for you. Try this:

<IconClose
  className="bubbleBin"
  alt="close bubble"
  height="100px"
  width="100px"
  viewBox="9 9 26 26"
/>

Here is a forked project with the change.

https://codesandbox.io/s/issue-styling-svg-component-8wwtw

These values seem to work nicely, you may be able to tweak them a bit more, if you need to use decimal values that's generally fine ( 9.5 for example).

It has nothing to do with React. SVG image has a predefined width and height from the viewBox , and will not scale with the width / height properties as a result. You can read more about how SVG images work here .

Your two options are to use transform: scale(X) on the image which is a bit of a hack, or you can check out this question to see how to properly change the SVG image viewBox . This is a much better option than transforming the image, but I provided both examples to give an understanding of why you're having an issue with width / height .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM