Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

css - Support 'background-size' property on older browsers?

Is there a way that I can use the CSS3 'Background-Size' property and then use something like Modernizr to ensure that it's supported in older browsers (in particular I want to use 'background-size: cover' option)?

I took a look at cssFx, which is mentioned from the Modernizr website, but this only seems to add vendor prefixes for browsers which need them to use a property, rather than allowing browsers such as IE8 to support the background size property.

Also looked at CSS3Pie, but that doesn't seem to currently support the background-size property.

[11/10/2011 - By older browsers I'm thinking mainly of IE7/8, but ideally I would like to cover FF3.6, etc.]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're right that background-size is not supported on a number of older browsers.

The typical solution to this is to simulate it using an additional <div> or even an <img> element positioned behind the element you want to have the background.

This can be achieved simply by using additional markup, but this solution has the disadvantage of meaning that you'll be using it for all browsers, instead of the background-size property. In other words, it means deliberately degrading your code for the sake of old browsers, which is not ideal.

If you want to use the CSS property for browsers that support it, you could use a bit of Javascript to generate the above markup, but only if required. This means that modern browsers can happily use background-size, and only older browsers will use the fallback.

There are a number of Javascript solutions to this available on the web (a quick google turned up the following: http://css-tricks.com/766-how-to-resizeable-background-image/ among others), but more importantly you need to know how to trigger it based on the browser.

This is where Modernizr comes in. The description you've given of Modernizr in the question is not entirely accurate. What it does is produce a set of CSS classes in your HTML markup and matching variables in your Javascript that represent all the browser features. These are boolean flags indicating whether the current browser supports.

So with Modernizr you can then check in Javascript whether the browser supports background-size or not, and only run the alternative javascript function if it doesn't support it.

if(!Modernizr.backgroundsize) {
    //do stuff here to simulate the background-size property for older browsers.
}

Hope that helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...