Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this SVG fit inside its parent DIV for small DIV sizes?

Tags:

svg

My expectation is that the triangle should be inside the container div. This works as expected for widths bigger than 14 pixels or so, but for small div sizes the SVG gets bumped down.

<div id="square" style="width: 9px; height: 9px; background-color: red">
    <svg viewBox="0 0 99 99" style="width:100%; height: 100%; fill: blue;">
        <polygon
            id="triangle"
            points="0,99 49,0 99,99" />
    </svg>
</div>

Fiddle here: https://jsfiddle.net/rpk6c6r0/4/

like image 950
Keith Carter Avatar asked Nov 16 '15 22:11

Keith Carter


People also ask

How do I make SVG fit to the parent container 100?

We use viewBox to make the SVG image scalable. viewBox = “0 0 100 100”: defines a coordinate system having x=0, y=0, width=100 units and height=100 units. Thus, the SVG containing a rectangle having width=50px and height=50px will fill up the height and width of the SVG image, and all the dimensions get scaled equally.

How do I fix SVG size?

Just set the viewBox on your <svg> , and set one of height or width to auto . The browser will adjust it so that the overall aspect ratio matches the viewBox .

How do I shrink an SVG file?

❓ How can I resize a SVG image? First, you need to add a SVG image file: drag & drop your SVG image file or click inside the white area to choose a file. Then adjust resize settings, and click the "Resize" button. After the process completes, you can download your result file.

What is viewBox in SVG?

The viewBox attribute defines the position and dimension, in user space, of an SVG viewport. The value of the viewBox attribute is a list of four numbers: min-x , min-y , width and height .


1 Answers

An <svg> element in HTML is set to display: inline by default. This can cause it to be affected by line-wrapping when space is constrained; the icon will wrap to the next line in the same way as a word in a paragraph.

Easiest fix, if you are positioning the SVG precisely, is therefore to set display: block.

https://jsfiddle.net/rpk6c6r0/6/

like image 194
AmeliaBR Avatar answered Sep 21 '22 23:09

AmeliaBR