How to make a background of a SVG element in a decent way?

7

I develop sites that have the company logo on SVG , but wanted to know how to easily test or force it to replace SVG when the browser does not support it. So I could have the PNG logo to replace.

  

Generally I put the SGV as the background of an element with   visibility in block and make an alternative CSS for IE8 and smaller,   Am I acting correctly?

    
asked by anonymous 27.02.2014 / 14:34

3 answers

8

If markup is an option

I am answer separately because they are of two distinct solutions with distinct implications and in a way this is an extensive response that lacks its independence.

By changing markup you're currently using, you can deal with the issue of SVG support without having to increment your stylesheet or script file with lines of code that only will serve a small percentage of visitors.

SVG and tag tricks

The solution presented is based on the fact that browsers make the image tag a nickname for the img tag, as explained in

27.02.2014 / 18:39
5

If JavaScript / jQuery is an option

You can ask the browser whether or not it supports SVG and the response to act accordingly:

Example in JSFiddle

/**
 * Detecta suporte ao SVG
 */
function suportas_SVG() {
    return !!document.createElementNS && !!document.createElementNS('http://www.w3.org/2000/svg', "svg").createSVGRect;
}

// Se não tem suporte ...
if (!suportas_SVG())
    $('.logo').css({
      "background-image" : "url(http://www.quatrocubos.com.br/img/qq.png)"
    });

The code in the suggested function is found in modernizr (English) source code would be my recommendation if you have to do many verifications of this sort for various types of support.

    
27.02.2014 / 17:24
2

If you hack css type this:

/* hack css para navegadores que não suportam svg */
background: url(http://www.quatrocubos.com.br/img/qq.png) top center no-repeat;
background: url(http://www.quatrocubos.com.br/img/qq.svg) top center no-repeat;

That's a decent way for me. (at least unavoidable).

EDIT 1

There are many ways, one that may suit what you want to be:

background-image: url(http://www.quatrocubos.com.br/img/qq.svg); /* Qualquer Browser */
background-image /*\**/: url(http://www.quatrocubos.com.br/img/qq.png); /* Internet Explorer 8 */
*background-image: url(http://www.quatrocubos.com.br/img/qq.png); /* Internet Explorer 6 e 7 */
_background-image: url(http://www.quatrocubos.com.br/img/qq.png); /* Internet Explorer 6 */

Note: You will not be covering all browsers, you will only be covering IEs.

    
27.02.2014 / 15:48