Skip to content

Instantly share code, notes, and snippets.

@exogen
Created September 27, 2016 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save exogen/0c9e6700992f53c045cca7283ffea2a3 to your computer and use it in GitHub Desktop.
Save exogen/0c9e6700992f53c045cca7283ffea2a3 to your computer and use it in GitHub Desktop.
Fix SVG heights
/*
* WebKit (possibly others; Firefox looks fine) does a bad job of scaling an
* SVG's aspect ratio such that its contents fill the extent of the space
* horizontally. If you're letting the browser determine the dimensions of your
* SVG, including the aspect ratio (e.g. by setting a percentage width and using
* `height: auto`), then you probably want to use `preserveAspectRatio="none"`
* in your SVG for the best results. But if you can't do that, you can at least
* bump up the SVG's height just enough for it to fill the `img` horizontally,
* letting the browser add the leftover padding to the top and bottom rather
* than the sides.
*/
$(document).ready(function() {
function fixHeights() {
$('img[src$=svg]').each(function(i, img) {
img = $(img);
img.height('auto');
// Give the SVG at least 1px and at most 2px of extra height to make up
// for the browser's bad aspect ratio padding the sides.
img.height(Math.ceil(img.height()) + 1);
});
}
var _raf;
// Do it on the next frame after a resize.
$(window).resize(function() {
window.cancelAnimationFrame(_raf);
_raf = requestAnimationFrame(fixHeights);
});
// ...and on ready.
fixHeights();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment