How to provide responsive design for svg?

2020-03-24 07:55发布

问题:

I am new to raphael. I wrote svg tag inside div. Please see this sample http://jsfiddle.net/dhana36/bvs6P/1/

Use the CTRL+ and CTRL- and you will find the difference.

HTML:

<div class="outer">
<svg height="640" version="1.1" width="100%" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100% 640" preserveAspectRatio="xMinYMin" style="overflow: hidden; position: relative; left: -0.625px;" class="stretchBar">
<desc style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">
Created with Raphaël 2.1.0
</desc><defs style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></defs>
<path fill="none" stroke="#000000" d="M228,109L228,110Z" stroke-width="200px" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path>

</svg>
</div>

css:

.outer{

    width:30%;
    height:30%;
}

How to implement svg responsive with content ?

回答1:

I don't believe this question deserves the downvote it received simply because it wasn't phrased from a perspective of understanding, so I am counteracting the downvote with an upvote.

SVG elements are intrinsically responsive within their defined viewbox (which, as Robert pointed out, must be defined absolutely). All you need to do is to define the viewbox over the area you want to work with, provide content that fills that area, and then make the width and height of the svg element relative to the size of its parent div (i.e., proportionally), and the SVG element will automatically scale its content to match.

Here is an example of a more sophisticated SVG behaving in a responsive fashion: http://jsfiddle.net/kevindivdbyzero/qMSLs/1/

The relevant items to notice are the svg definition

<svg version="1.1" width="100%" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 600" preserveAspectRatio="xMinYMin" style="overflow: hidden; position: relative; left: -0.5px;" class="stretchBar">

and the CSS style for your container element (div.outer) and the svg element itself:

.outer{    
    width:50%;
    height:50%;
}

.adaptive-svg {
    width: 100%;
    min-width: 250px;
    height: auto;
}