Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fit <svg> to the size of <object> container

Tags:

html

css

svg

size

I have this markup:

#widget1 {
    height:100px;
    width:200px;
}

<div class="widget" id="widget1">
    <object data="foo.svg" type="image/svg+xml" />
</div>

I managed to make the <object> element fill up the outer <div>, but the inner foo.svg file has its own ideas how big it is. I need foo.svg (which consists of an <svg> element, of course) to be the same size as <object> and <div>.

like image 852
tillda Avatar asked Jan 19 '11 15:01

tillda


People also ask

How do I make SVG fit in Div?

Set the CSS attribute position:absolute on your <svg> element to cause it to sit inside and fill your div. (If necessary, also apply left:0; top:0; width:100%; height:100% .)

Can you use object-fit on an SVG?

By default, just like with object-fit , the browser will fit the viewBox inside of the SVG viewport (or “box”) by containing it inside of it, such that the entire viewBox — and, thus, all the contents of the SVG — are visible inside the viewport.

How do you scale SVGs?

Any height or width you set for the SVG with CSS will override the height and width attributes on the <svg> . So a rule like svg {width: 100%; height: auto;} will cancel out the dimensions and aspect ratio you set in the code, and give you the default height for inline SVG.

How make SVG full width?

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.


1 Answers

This is answered (with examples) in the svg primer.

tl;dr summary:

  • remove 'width' and 'height' attributes on the svg root, and add a 'viewBox' attribute with the value "0 0 w h", where w and h are the absolute values usually found in the width and height attributes (note that percentages and other units aren't allowed in the viewBox attribute)
like image 162
Erik Dahlström Avatar answered Sep 20 '22 04:09

Erik Dahlström