Skip to content

Instantly share code, notes, and snippets.

@Heydon
Last active August 31, 2018 16:36
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Heydon/369185d08d9ce2426f01863625e95525 to your computer and use it in GitHub Desktop.
Save Heydon/369185d08d9ce2426f01863625e95525 to your computer and use it in GitHub Desktop.
(function () {
// If the browser supports Microsoft High Contrast Mode...
if (window.matchMedia('(-ms-high-contrast: none), (-ms-high-contrast: active)').matches) {
// Get all the SVGs on the page except the symbol defs
var svgs = document.querySelectorAll('svg:not(.defs)')
// ... iterate over SVGs
Array.prototype.forEach.call(svgs, function(svg) {
// Set preserveAspectRatio to 'XMidYMin slice'
svg.setAttribute('preserveAspectRatio', 'xMidYMin slice')
// Turn the viewBox values into an array
var viewBox = svg.getAttribute('viewBox').split(' ')
// Calculate padding value needed (width/height x 100)
var padding = (viewBox[2] / viewBox[3]) * 100
// Set inline styles
svg.setAttribute('style', 'width: 100%; padding-bottom: ' + padding + '%; height: 1px; overflow: visible')
})
}
}());
@tedw
Copy link

tedw commented Sep 12, 2017

Nice idea! I think you need to flip the padding ratio, though:

var padding = (viewBox[3] / viewBox[2]) * 100

For example, a 4:3 SVG should have 75% padding, not 133% 😉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment