Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change width of height of SVG with CSS?

Tags:

html

css

svg

I have a CRA React App.

How do you change the width and height of an SVG without preserving aspect ratio (e.g. width 500px height 10px)?

import ornament from '../../assets/img/ornament.svg';

<img src={ornament} style={{width: '500px', height: '20px'}} />

This preserves aspect ratio and only changes size. I want it to transform to 500px width and 20px height. So original 400px 400px => 500px 20px.

EDIT: example on codesandbox: https://codesandbox.io/s/40xj3zv5w7 , the image gets really small instead of 400px width and 10px height.

like image 895
J. Reku Avatar asked Sep 06 '25 03:09

J. Reku


2 Answers

You can't resize only width, like a regular image, because svg are vectors, and they scale. You need to set preserveAspectRatio(none)

When you are working with just HTML, you can do tis:

<img src="your.svg#svgView(preserveAspectRatio(none))" />

With React, you can do it like this:

import React, {Component} from 'react';
import ornament from '../../assets/img/ornament.svg';

class App extends Component {
  ...

  render() {
    const svgPath = `${ornament}#svgView(preserveAspectRatio(none))`;
    return (
      <img src={svgPath} width="500px" height="20px"/>
      )
  }
}

export default App;
like image 129
Damian Peralta Avatar answered Sep 09 '25 03:09

Damian Peralta


You can use css transform: scale(sx, sy)

sx = 500/400
sy = 20/400
like image 42
Domenik Reitzner Avatar answered Sep 09 '25 04:09

Domenik Reitzner