Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

css - How to make a <svg> element expand or contract to its parent container?

The goal is to have the <svg> element expand to the size of its parent container, in this case a <div>, no matter how big or small that container may be.

The code:

<style>
    svg, #container{
        height: 100%;
        width: 100%;
    }
</style>

<div id="container">
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" >
         <rect x="0" y="0" width="100" height="100" />
    </svg>
</div>

The most common solution to this problem seems to be setting the viewBox attribute on the <svg> element.

viewBox="0 0 widthOfContainer heightOfContainer"

However, this does not seem to work in cases where elements within the <svg> element have predefined widths and/or heights. For example, the <rect> element, in the above code, has its width and height explicitly set.

So the obvious solution is to use % widths and % heights on those elements as well. But does this even have to be done? Especially, since <img src=test.svg > works fine and expands/contracts without any problems with explicitly set <rect> heights and widths.

If elements like <rect>, and other elements like it, have to have their widths and heights defined in percentages, is there a way in Inkscape to set it so that all elements with the <svg> document use percentage widths, heights, etc.. instead of fixed dimensions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The viewBox isn't the height of the container, it's the size of your drawing. Define your viewBox to be 100 units in width, then define your rect to be 10 units. After that, however large you scale the SVG, the rect will be 10% the width of the image.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...