Brandon Burchett
Brandon Burchett

Reputation: 35

Cannot display linear gradient as a background image on a html page

<svg version="1.1" xmlns="http://w3.org/2000/svg">
    	<title> Background </title>
    	<text>
    		<LinearGradient id="g" x1="200%" x2="0%" y1="50%" y2="0%">
    		<stop style = "stop-color: green;" offset="0"/>
    		<stop style = "stop-color: white;" offset="1"/>
    		</LinearGradient>
    	</text>
    	<rect style = "fill: url(#g);" width = "100%" height = "100%"/>
    </svg>

The output of this code is either broken image, or the Title "Background" and I do not see what's wrong with it.

Upvotes: 1

Views: 45

Answers (2)

Robert Longson
Robert Longson

Reputation: 123985

You've two issues which affect standalone SVG only

  • the SVG namespace is incorrect so the file is not recognised as an SVG file. You're missing www from the namespace.
  • standalone SVG files are case sensitive so we need to write linearGradient

And this one is a bug even when you embed SVG in html.

  • you can't make a linearGradient the child of a <text> tag. We can use <defs> instead. In theory we could omit the <defs> tag, although I think Safari isn't keen on that.

which leaves us with this...

<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
    <title> Background </title>
    <defs>
        <linearGradient id="g" x1="200%" x2="0%" y1="50%" y2="0%">
        <stop style = "stop-color: green;" offset="0"/>
        <stop style = "stop-color: white;" offset="1"/>
        </linearGradient>
    </defs>
    <rect style = "fill: url(#g);" width = "100%" height = "100%"/>
</svg>

Upvotes: 1

Temani Afif
Temani Afif

Reputation: 272618

You should use defs for the gradient. You may also consider viewbox and width/height:

<svg version="1.1" xmlns="http://w3.org/2000/svg" viewBox="0 0 200 100" width="200">
    <title> Background </title>
    <defs>
        <LinearGradient id="g" x1="200%" x2="0%" y1="50%" y2="0%">
        <stop style = "stop-color: green;" offset="0"/>
        <stop style = "stop-color: white;" offset="1"/>
        </LinearGradient>
    </defs>
    <rect fill="url(#g)" x="0" y="0" width="200" height="100" />
</svg>

Upvotes: 0

Related Questions