Usually the browser renders the svg images properly but in chrome the browser doesn't detects the css3 scale and return a poor image. This must be because css scale is a new technology... Is there any way to select the render quality?
Sorry for my english, I'm studying it!
There are a couple of workarounds for this, none as easy as setting a render quality directive, I'm afraid. The most straightforward workaround would be inserting the actual SVG instead of using it inside an img tag.
Your html would look like...
<svg>
...
</svg>
And your css would look like...
svg {
-webkit-transform: scale(2);
}
Here is a demo: http://jsfiddle.net/EgsGe/
Related
First time posting here, so treat me gently. :)
I have an SVG image on my site which has a transparent background -
<img class="img-responsive center-block" src="images/pritchservices.svg" alt="Pritch Services Logo" />
Works beautifully on my site. However, due to the transparency, when that image loads in google image search results, due to the transparency, looks terrible.
I have an alternative image (using for fb Open Graph crawler) which is here -
Pritch Services Full Logo
In my crazy mind, this is what I had as a plan:
Redo the SVG in Illustrator to include the background color (as per the fb OPen Graph image) - this would then mean the image result in Google would be as expected
Have some CSS within my site to set the background color of the SVG to transparent, so it displays nicely (as it currently does on the site)
I am assuming I can't just put the SVG markup inline, as although this would give me what I wanted on the page, it wouldn't load the image AT ALL on google image search results?
Is this the way to go, if so, any suggestions on how to implement please; or is there an alternative solution I haven't thought of? Or am I just being too picky?!
Thanks in advance everyone...
You can't include an SVG via <img> and style it with CSS in your parent document.
You can't style the contents of an <img>, even if it is an SVG
CSS doesn't apply across document boundaries
You have a few options.
Include the version with a background in your page. And then hide it and replace it with the transparent-background version via CSS.
<div class="logo">
<img src="logo-with-background.svg" ... />
</div>
.logo img {
display: none;
}
.logo {
background-image: url(logo-without-background.svg);
}
Include the background version using <object> then use the DOM to find the background element and hide it.
var object = document.getElementById("myObject");
var svgDoc = myObject.contentDocument;
svgDoc.getElementById("bg").setAttribute("display", "none");
Apply a clipping path to the backgrounded version as #Obink suggests. It would work, but it is not the easiest solution though. And it won't work on older browsers that don't support clip paths.
I've just read this article from Google Web Fundamentals on using SVG for icons. Two approaches are given. The first is the inline approach. For example:
<svg version="1.1" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="32" height="32" viewBox="0 0 32 32">
<path d="M27 4l-15 15-7-7-5 5 12 12 20-20z" fill="#000000"></path>
</svg>
Demo
The second approach is to use an image tag such as: <img src="credit.svg">
I'm also aware SVGs can be defined as:
an object
an embed tag
an iframe
They can also be set as background images in CSS.
My question:
What are the advantages and disadvantages of each approach?
The advantages of using img, object, embed and other with SVG backgound:
<img class="icon icon_foo"> is much shorter and beautiful than inline SVG — <svg class="icon icon_foo"><use xlink:href="#foo"></use></svg>
The disadvantages of using img, object, embed and other with SVG backgound:
you absolutely have no any control of styling options — you cannot set color, outline width and outline color — all you can do is just to put SVG as background and set styles right in SVG file one time
you cannot reuse your icons because of statement above (if you have one icon in two-three-twenty different places on your web page and it should be colored in different colors the only way is to create two-three-twenty equal SVG files with only one difference — fill option ;)
The advantages of using inline SVG:
reusability (eg. you have only one Twitter SVG icon and you can use it everywhere with any styles, so, you do not need 2 or 3 same SVG files just with different fill attribute in each SVG file)
complete control over your icon appearance — styles, colors, sizes
The disadvantages of using inline SVG:
it is longer than IMG and does not look beautiful
Caching:
Using AngularJS or any other framework:
<ng-include src="'icons.html'"></ng-include>
Using VanillaJS:
file icons.js on your server:
var icons = '<svg><symbol id="icon-XXX" viewBox="0 0 256 256"><path d="{here_goes_compounded_path}"></path></symbol></svg>';
in HEAD section:
<script src="icons.js"></script>
<script>
document.getElementById('icon-placeholder').innerHTML(icons);
</script>
right after the BODY tag:
<div id="icon-placeholder" style="display:none;"></div>
Fiddle with the best approach:
Right after body tag place all your SVG icons (or use Angular's or any other framework ng-include):
<body>
<svg style="display:none;">
<symbol id="icon-XXX" viewBox="0 0 256 256"><path d="{here_goes_compounded_path}"></path></symbol>
<symbol id="icon-YYY" viewBox="0 0 256 256"><path d="{here_goes_compounded_path}"></path></symbol>
</svg>
In any place on your web page put an icon:
<svg class="icon icon_red">
<use xlink:href="#icon-XXX"></use>
</svg>
<svg class="icon icon_green">
<use xlink:href="#icon-YYY"></use>
</svg>
<svg class="icon icon_blue">
<use xlink:href="#icon-XXX"></use>
</svg>
In CSS:
.icon {
width: 16px;
height: 16px;
fill: currentColor;
}
.icon_red { fill: #f00; }
.icon_green { fill: #0f0; }
.icon_blue { fill: #00f; }
.icon_foo {
stroke: #000;
stroke-width: 8;
fill: #0f0;
}
Do not forget about magic "currentColor" CSS variable — it will color your SVG icon in current text color:
fill: currentColor;
Further must read:
any front-end RSS feeds: inline SVG is about a year old discussion
http://tympanus.net/codrops/2013/11/27/svg-icons-ftw/
http://tympanus.net/Tutorials/ResponsiveSVGs/index.html
http://ianfeather.co.uk/ten-reasons-we-switched-from-an-icon-font-to-svg/
The answer is, should you be worrying about who's looking at your code? SVG inline will always bloat your HTML depending how complex the drawn SVG is. Inline does in some respect have better performance implications due to the fact it's being loaded directly with the HTML as opposed to loading the SVG externally when using it, for example, as an <img>. However, it's practically unnoticeable and should be the least priority when coming down to performance.
The disadvantages of inline SVG:
Bloats code
Cannot be cached by the browser
No fallback available
IE, without XHTML (and that's if SVG is supported) doesn't support SVG technically, though this is a low priority and we shouldn't care about it in the current world of the web. Still, it's primarily a disadvantage to those ancient warriors.
The advantages of inline SVG:
I can't think of any, seriously. Other nosey people can see it?
Actually, those without CSS enabled can see it.
The disadvantages of using <img> with SVG:
Again, limited fallback support (You can use Modernizr to replace the .svg extension with .png, but then you rely on the user having javascript enabled)
Limited styling options with the SVG
The advantages of using <img> with SVG:
Semantically better than bloating all your code
Readability in your codebase is better for a) yourself and b) other developers who might be working on the project too.
Better maintainability.
Alternative methods:
You can use the following methods you provided in your question (and below) about using <object>, <embed> and <iframe>, although, these also limit the use cases and would need declaring in every HTML document, which can get messy as you progress in a project, whether it be large or small.
The 'better approach':
Disclaimer: By no means is the a 'better for everyone' method. This is simply how I would declare my SVG elements for reusability and gives me full control of identifying my assets when using SVG.
The biggest pitfall for using inline SVG in your HTML is the fallback support. I have always used SVG as a background image (unless it's a webfont I'm using for icons etc.), purely because I can create a .png version and write the fallback in my CSS, like so:
.icon {
display: inline-block;
vertical-align: baseline;
background-repeat: no-repeat;
background-position: center center;
background-size: contain;
}
.icon--16 {
width: 16px;
height: 16px;
}
/* Always declare the PNG before the SVG. */
.icon--foo-blue {
background-image: url('foo-blue.png'); /* Fallback */
background-image: url('foo-blue.svg'), none; /* Modern */
}
.icon--foo-green {
background-image: url('foo-green.png'); /* Fallback */
background-image: url('foo-green.svg'), none; /* Modern */
}
Then, use it:
<span class="icon icon--16 icon--foo-blue"></span>
<span class="icon icon--16 icon--foo-green"></span>
The disadvantage of this:
No support for CSS styling, however, we should be aware of why we are styling SVG in our CSS. If you're using more colours than your website uses then there is generally something not right. Declaring 4 files for the same SVG but in a different colour is not bad practise as it allows us to cache these in the browser for later, throughout any webpage which in the answer constructed below completely removes this purpose. Take advantage of caching on the server/within the browser!
And of course, it depends what kind of image you are trying to render to the user. If you're going to use large SVG files for showcasing something, for example, I would probably think about what kind of users I'm targeting; that being, those on modern browsers because I might want to include fancy inline SVG animations etc.
It really depends on personal preference too. There is no major red flags for using SVG inline to this day, but we still have some heart for those back in the stone ages of less-than IE9. And, not to forget, Android is quirky with SVG too!
EDIT: It seems like there is a large debate over inline SVG's. One word of warning is, there is no reusability doing this. If you're showcasing a fancy website with fancy SVG animations, then by all means, build your entire page in SVG for crying out loud. No one is stopping you. It's personal preference. But for icons, where you will more than likely reuse throughout a project, please, declare them outside your HTML as it gives you greater control in the long run and not because you need a different colour here and there. Think about it. :)
What I tend to do nowadays is wrap it inside a Web Component:
/assets/svg/hex.js
export default `<svg>...</svg>`;
/my-svg.js
class MySvg extends HTMLElement {
connectedCallback() {
const id = this.getAttribute('id');
import(`./assets/svg/${id}.js`).then(svg => {
this.innerHTML = `
${svg.default}
`;
});
}
}
customElements.define("my-svg", MySvg);
index.html
<my-svg id="hex"></my-svg>
This way I get the advantages of inline svg, lazy loading due to dynamic import and without the bloat in the code I'm supposed to work on / maintain, with just one custom element. And the id attribute makes clear which svg I'm loading.
I've been looking at using SVGs on my site, I wish to color them via CSS, I've looked at some blogs which suggest using the object tag:
<object type="image/svg+xml" data="/static/test.svg">Your browser does not support SVG</object>
I'm now trying to do two things, colour the svg, I've tried using:
fill: red;
But no luck.
And size it, I've tried this on the object:
width="150px"
But no luck.
You have to use an <svg> object to make it possible. A good solution could be to use the iconic's SVGInjector so you can load it from another file and keep your code clean.
I am trying to manipulate an external .svg file via CSS.
HTML
<body>
<div class="mysvg">
<img src="decho.svg" alt="decho" width="200px"></img>
</div>
</body>
CSS
div.mysvg img {
opacity: .3;
transition: opacity 1s linear 0s;
}
div.mysvg img:hover {
opacity: 1;
}
This code works for opacity, but not for fill or other svg specific attributes like stroke. I am aware I can't do that with an img tag, but I've been looking for hours and I can't find the correct way to do it with svg or object.
So basically, my questions is, how do I achieve the same result as the code which I linked, but to be able to manipulate fill, stroke etc. properties and it must be an external file, not just an inline svg code pasted in the html.
If someone is able to show me the correct way to do it, I'd be most grateful. Thanks.
EDIT:
I managed to do it by adding a css inside the .svg file itself. It must be right after the svg opening tag.
<svg ...>
<style type="text/css" media="screen">
<![CDATA[
g {
fill: yellow;
stroke: black;
stroke-width: 1;
transition: fill 1s linear 0s;
}
g:hover {
fill: blue;
}
]]>
</style>
<g>
<path ...>
</g>
</svg>
You also need to insert it as an object in the html, otherwise it won't work.
<object data="decho.svg" type="image/svg+xml">
Hopefully this helps to someone looking for an answer like mine in future. This is what helped me http://www.hongkiat.com/blog/scalable-vector-graphic-css-styling/.
This is in my opinion the greatest flaw in svg: sandboxing.
Svg files are sandboxed: in their own document, which is why a typical 'fill:' style will not apply. Likewise, the css you write in your svg will not apply to the rest of your site.
Adding css directly to an svg: Not a good solution as you will end up rewriting the css in every svg you use.
The real solution: An "icon-system". Svg font-face or svg sprites. Read more about them here.
The reason opacity works: Opacity applies to the svg object/frame itself, not the contents of the svg (which are inaccessible).
I should also note that no matter how you load those svg's, inline, by reference, in an object, as a background, you will not be able to get inside the sandbox. This is why converting them to a font or using sprites is necessary for using hover, focus, and other effects/transitions.
This is possible providing the SVG is hosted on the same domain (thanks #FabienSnauwaert) and it does not have a fill colour defined on itself, and you do not contain a parent selector within the CSS. For example:
I have the following files:
icon-sprite.svg (my external sprite of SVGs)
buttons.scss
test.html
icon-sprite.svg
I have omitted the other SVGs for clarity.
<svg xmlns="http://www.w3.org/2000/svg" style="width:0;height:0;visibility:hidden;">
<symbol viewBox="0 0 1500 828" id="icon-arrow-3pt-down">
<title>arrow-3pt-down</title>
<path d="M1500 0H0l738.9 827.7z"/>
</symbol>
</svg>
test.html
<button class="button--large">
Large button
<svg class="svg" width="20px" height="20px">
<use xlink:href="icon-sprite.svg#icon-arrow-3pt-down"></use>
</svg>
</button>
buttons.scss
.svg {
fill: red;
}
This would not work if I was to use body .svg due to shadow DOM boundaries.
See this CSS Tricks article for more info
I recently ran into this. While SVGs are not part of the DOM for some arbitrary reason, you can move them to the DOM with a bit of javascript:
<object type="image/svg+xml" data="illustration.svg"
onload="this.parentNode.replaceChild(this.contentDocument.documentElement, this);">
</object>
This will replace the <object> with an inline after it has loaded. In case javascript is disabled, it falls back to an <object> tag, and the svg will not be themed. In my case, the styling was for a javascript-controlled dark theme, so having the correct fallback means no theming issue.
Other options considered (xlink is a good one for sprites):
Use an external library to load svgs inside the DOM (the above js is simple enough IMO)
use svg filters for chroma-keying. That makes svgs more complex to edit, might use more resources to perform the filtering, and is less flexible.
Note that I am not sure of the security implications, better save this for files you control.
Unfortunately, there's no built-in feature in Web Standards that makes it possible. SVG Symbols is an option but doesn't work with files hosted on CDNs. Additionally, you need to ensure that SVG files are defined properly to make use of <use> tag.
I have created a library, svg-loader, that makes it easier to achieve this. It uses Javascript but it's only 3kb and it's loaded asynchronously, so the impact on performance is negligible. It's plug 'n play, so you don't need to do anything except including the <script> tag.
Here's a Codepen example.
I have made an svg image that I am using as a background image. I does not work in IE8 and below (as expected), and I thought I could use something use like: http://twostepmedia.co.uk/svgeezy/ or http://code.google.com/p/svgweb/. However, none of these support SVG as a background-image/background, only IMG and Object etc.
Code:
background:url('img/bck_hero.svg');
How can I get an SVG as the background in IE8/7 or have a fallback image? Is there a javascript library that could do this?
Thanks a lot,
Harley
One way is to detect support for svg with javascript and then style differently depending on that.
If you use modernizr you could do it like this in your stylesheet:
#myElm.svg { background:url('img/bck_hero.svg'); }
#myElm.no-svg { background:url('img/bck_hero.png'); }