Anders Lindén
Anders Lindén

Reputation: 7303

Cannot stretch svg background image, aspect ratio will be preserved

I am using svg as background image and I want it to be stretched to 100% 100%.

However, it seems like both Chrome and firefox are doing their best to retain the aspect ratio of the svg and instead shrink it in the other width.

Normal size

div
{
    background: url(image.svg) no-repeat;
    background-size: 100% 100%;
    width: 14rem;
    height: 4rem;
}

Normal size

Double width

div
{
    background: url(image.svg) no-repeat;
    background-size: 100% 100%;
    width: 28rem;
    height: 4rem;
}

Double as wide

Double height

div
{
    background: url(image.svg) no-repeat;
    background-size: 100% 100%;
    width: 14rem;
    height: 8rem;
}

Double height

How can I instead have that svg stretched?

svg contents:

<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 18.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<svg version="1.1" id="Lager_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 371.7 102.8" enable-background="new 0 0 371.7 102.8" xml:space="preserve">
<polygon fill="#EF9104" points="370.4,100.5 0,100.5 0,0 269.4,0 "/>
</svg>

Upvotes: 17

Views: 6445

Answers (4)

Robert Longson
Robert Longson

Reputation: 124059

You can use an SVG Fragment Identifier if you don't want to edit the SVG file itself to remove the viewBox or add preserveAspectRatio="none"

For example

div
{
    background: url(image.svg#svgView(preserveAspectRatio(none))) no-repeat;
    background-size: 100% 100%;
    width: 28rem;
    height: 4rem;
}

Upvotes: 2

Chase
Chase

Reputation: 2306

For those who need to hear it, like me, just now... because I haven't finished my coffee...

Make sure preserveAspectRatio="none" is on your top-level svg element (rather than directly on the path or shape).

/facepalm

Upvotes: 0

ceindeg
ceindeg

Reputation: 444

Appreciate that this is an old question but I was having issues with this so wanted to post some further information in case it helps anyone else...

<svg preserveAspectRatio="none"> this only works when a viewBox attr is provided, for instance: <svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" viewBox="0 0 1920 1152">

"preserveAspectRatio only applies when a value has been provided for viewBox on the same element. For these elements, if attribute viewBox is not provided, then preserveAspectRatio is ignored." https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/preserveAspectRatio

Hope this helps someone else!

Upvotes: 2

Paulie_D
Paulie_D

Reputation: 115046

You should add

<svg preserveAspectRatio="none">

to your SVG.

MDN Reference Link

<none>

Do not force uniform scaling. Scale the graphic content of the given element non-uniformly if necessary such that the element's bounding box exactly matches the viewport rectangle.

Upvotes: 25

Related Questions