Sizing an SVG to its parent’s aspect ratio
I’ve run into this before, but when I ran into it this yesterday I couldn’t remember the solution. You’re welcome, future self, for writing it down.
Sometimes, you want an SVG to perfectly scale to the size of its parent, regardless of any intrinsic aspect ratio the SVG and its viewBox might have.
You drop in your SVG and tell it to fill its container:
svg {
display: block;
width: 100%;
height: 100%;
}
And…it doesn’t work quite right. It this case, the viewBox has an intrinsic aspect ratio of 1:1. The browser lets it go below that, so it’s fine when the container is taller than it is wide, but when the container’s aspect ratio goes above the intrinsic aspect ratio (i.e., wider than it is tall), it adds extra height to force it to that intrinsic ratio. So in this case, the SVG is forced, and forces its parent, to be a square when the container should be wider than it is tall.
See the Pen Sizing an SVG to its parent – bad example by Noah (@noleli) on CodePen.
Thankfully, the fix is simple: add overflow: hidden to the container.
See the Pen Sizing an SVG to its parent – good example by Noah (@noleli) on CodePen.
🎉
Now, it’s not always a perfect fix because sometimes you want an SVG to be allowed to overflow, especially for showing strokes near the edges. If anyone has any better suggestions, let me know!