This week we came across an interesting technical problem: how do you make an SVG that’s being used as a background-image respond to the width of its container, yet also scale its height depending on the child elements within?
Here’s an example to illustrate the problem:
There’s an SVG background image attached to an element with a header and paragraph within. The problem is that sometimes we might not have a paragraph inside this module, we might have buttons or perhaps a byline instead. If we’re designing a maintainable system however, then we ought to make sure that our system plans for these sorts of content problems ahead of time.
But as you can see above, the SVG background will stick to its intrinsic proportions and refuse to scale vertically to accommodate these edge cases. In this case we want to break those proportions so that the background image stretches to the full height of the element, like this:
Strangely enough I couldn’t find any ready made solutions so I opened up the SVG in a text editor and after some digging around I discovered the preserveAspectRatio attribute. By adding preserveAspectRatio=”none” to the SVG element itself, whilst also making sure to remove all width and height parameters that might have been automatically set by an app such as Illustrator, the background will then scale both horizontally and vertically depending on the content within. Yay!
I’ve hooked up a quick example of this on Codepen, and it seems to work relatively well across various browsers. Remember though that this is obviously only suitable for browsers that support SVG, but with Modernizr we can test for this and prepare an appropriate fallback, like serving a background-color instead.