Reputation: 529
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.
Upvotes: 4
Views: 8547
Reputation: 21
The least complicated method I found: https://codepen.io/copist/pen/vLLmPB
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.0" x="0px" y="0px" width="48px" height="48px" viewBox="0 0 48 48" style="null" class="whateverClassYouWish" >
.whateverClassYouWish {
width: 512px;
height: 512px;
}
Upvotes: 1
Reputation: 1866
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;
Upvotes: 3
Reputation: 1613
You can use css transform: scale(sx, sy)
sx = 500/400
sy = 20/400
Upvotes: 1