Cross browser SVG preserveAspectRatio

后端 未结 5 797
渐次进展
渐次进展 2021-02-01 18:40

I\'m trying to have a SVG graphic inside an tag that would fit (without crop) inside the tag with preserved aspect ratio. I created t

相关标签:
5条回答
  • 2021-02-01 18:50

    Seems like I found the solution:

    You need to keep the width and height properties in the SVG.

    <svg
        width="580"
        height="220"
        viewBox="0 0 580 220"
        preserveAspectRatio="xMidYMid meet"
    >...</svg>
    

    And to make it work on IE 9 you need to specify at least one dimension of the <img /> tag.

    <img src="your.svg" style="width: 100%" />
    

    This seems to be working everywhere.

    0 讨论(0)
  • 2021-02-01 18:50

    Just an additional suggestion: Using an attribute selector based on the .svg filename suffix might be useful in cases where you need this behavior on all your svg content, and don't have control over the markup.

    For example

    img[src$=".svg"] {
        width:100%;
    }
    
    0 讨论(0)
  • 2021-02-01 19:09

    The solution in my case was using Peter Hudec's answer, but because of using width: 100%; on the <img /> tag, which broke the layout on every non-IE9 browser, I added a IE9-only CSS hack (width: 100%\9\0;). Hope this addition will help someone. :-)

    Even using the preserveAspectRatio="xMidYMid meet" was not neccessary.

    (I wanted to add only a comment, and not answer, but no reputations yet to do so :-)

    0 讨论(0)
  • 2021-02-01 19:11

    I solved it by setting the following CSS to the :

    width: 100%; max-width: (desiredwidth in px)

    0 讨论(0)
  • 2021-02-01 19:14

    Just thought that I would add how I stepped into a solution. I had trouble figuring out some of the issues at first.

    1. Edit your SVG file to remove the hard-coded height and width attributes. (with simple text editor)
    2. Apply width:100% css to your svg image to make IE display it like other browsers. (as big as it's container)
    3. Use css on your image container for consistent results!

    I made a page to describe it in more detail at http://ivantown.com/posts/svg-scaling-with-ie/

    0 讨论(0)
提交回复
热议问题