【问题标题】:How to change width of height of SVG with CSS?如何使用 CSS 更改 SVG 的高度宽度?
【发布时间】:2018-12-14 21:59:55
【问题描述】:

我有一个 CRA React 应用程序。

如何在不保留纵横比的情况下更改 SVG 的宽度和高度(例如,宽度 500 像素高度 10 像素)?

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

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

这会保留纵横比,仅更改大小。我希望它转换为 500px 宽度和 20px 高度。所以原来的 400px 400px => 500px 20px。

编辑:codesandbox 上的示例:https://codesandbox.io/s/40xj3zv5w7,图像变得非常小,而不是 400 像素宽和 10 像素高。

【问题讨论】:

标签: html css svg


【解决方案1】:

您不能像普通图像那样仅调整宽度,因为 svg 是矢量,并且它们缩放。您需要设置 preserveAspectRatio(none)

当您只使用 HTML 时,您可以这样做:

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

使用 React,您可以这样做:

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;

【讨论】:

    【解决方案2】:

    你可以使用 css transform: scale(sx, sy)

    sx = 500/400
    sy = 20/400
    

    【讨论】:

      【解决方案3】:

      我发现的最简单的方法: 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;
      }
      

      【讨论】:

        猜你喜欢
        • 2014-04-01
        • 1970-01-01
        • 2014-12-11
        • 2022-01-15
        • 2020-11-08
        • 2015-12-24
        • 2016-09-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多