Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scale inline SVG to parent containers width and height automatically?

Tags:

html

css

svg

I am trying to build a wavy box using svg. Something like this:

Some wave

I have drawn it in a vector application and set the size of the document to 500 x 200. Now, I copy the SVG contents into an inline SVG tag. So, the overall markup looks like the following:

<div class="hero-wave">
    <svg width="100%" height="100%" viewBox="0 0 500 200" version="1.1" xmlns="http://www.w3.org/2000/svg">
        <g fill="none" fill-rule="evenodd">
            <path d="M0,0.8828125 C0,0.8828125 21.5375284,2.70107724 30.175,8.11815895 C70.4419893,33.3720274 173.689709,104.747595 239.525,104.747595 C306.457042,104.747595 408.933103,43.7500826 451.921875,21.6893757 C494.910647,-0.371331192 500,8.11815895 500,8.11815895 L500,200.882812 L0,200.882812 L0,0.8828125 Z" id="Rectangle" fill="#595CA5"></path>
        </g>
    </svg>
</div>

When I add the width and height attributes, the SVG looks very small but I want the illustration to scale to the width of the container. The css for hero-wave div is like the following

.hero-wave {
    position: absolute;
    bottom: 20px;
    left: 0px;
    right: 0px;
    width: 100%;
    height: 20%;
}

How can I make the SVG to just fit the container perfectly, without any overflows. When I remove the width and height attribute from SVG, I get a very big version of the illustration and the bottom keeps overflowing:

overflowing SVG

How can I make it so that the SVG fits in that grey area without overflowing (the grey area is hero wave container)?

I am very new to SVG and there is no guide that I have been able to find that explains how SVGs work in terms of resizing. Do they try to keep the aspect ratio? If someone can shed a light on me on this matter, I would really appreciate it.

EDIT: If I make it so that the aspect ratio is the same, the illustration still overflows the parent container.

like image 313
Gasim Avatar asked Oct 18 '22 09:10

Gasim


1 Answers

You can set width: 100% & height: auto in svg:not(:root) selector for this. check updated snippet below.

.hero-wave {
    position: absolute;
    bottom: 20px;
    left: 0px;
    right: 0px;
    width: 100%;
    height: 20%;
}
svg:not(:root) {
    width:100%;
    height: auto;
}
<div class="hero-wave">
    <svg width="100%" height="100%" viewBox="0 0 500 200" version="1.1" xmlns="http://www.w3.org/2000/svg">
        <g fill="none" fill-rule="evenodd">
            <path d="M0,0.8828125 C0,0.8828125 21.5375284,2.70107724 30.175,8.11815895 C70.4419893,33.3720274 173.689709,104.747595 239.525,104.747595 C306.457042,104.747595 408.933103,43.7500826 451.921875,21.6893757 C494.910647,-0.371331192 500,8.11815895 500,8.11815895 L500,200.882812 L0,200.882812 L0,0.8828125 Z" id="Rectangle" fill="#595CA5"></path>
        </g>
    </svg>
</div>
like image 157
Super User Avatar answered Oct 21 '22 01:10

Super User