Cross-Browser Gradient Backgrounds


Recently, one of the websites I work on was given a makeover and I was asked to implement the design. One of the features it called for was rounded-cornered gradient backgrounds. Rather than turning the design down, I took up the challenge to try to implement it.

Looking around on the internet, there’s a little bit about how to go about that in a cross-browser way, but I thought I’d document it here.

The basic idea I took is to use an SVG as the background. Unfortunately, IE doesn’t support SVG’s and most of the browsers that do support them didn’t support them as backgrounds at time of writing. Fortunately, we can mess with CSS and HTML to display the SVG as an image behind the content, while at the same time providing a fallback for IE.

The basic idea, is to show the SVG after the content, then push it up behind the content with some absolute/relative positioning, so we write code similar to:

<div id="svg_outside">
    <div id="svg_content"></div>
    <div id="svg_background"></div>
</div>

Give the outside div a “position:relative” and the background div “position:absolute” and you’re all set. Put whatever you want for a background in the background div and your content in the content div (funnily enough).

While this doesn’t look nearly as clean as having just a single div with the background set to the svg, it does allow us a lot of flexibility to deal with IE. Since IE can’t natively handle SVG’s (yet), we can use a gradient filter on the background div. Alternatively, we could use some VML. You could even use a video as a background if you so felt like it 🙂

Check out http://eion.robbmob.com/svgdemo/ for an example.

There can be issues with the Adobe SVG plugin taking over sometimes.

Can’t be bothered writing about this any more, so I’m just gonna post it. Its been sitting in my drafts folder for long enough 🙂

Comments are closed.