SVG images linked or inlined in HTML5 documents is a practice that is relatively young (by web standards), but I believe it's important that it matures quickly. How should modern browsers size either type of svg image that states just their aspect ratio (as per their viewBox
), and where the parent HTML document just has either (but not both) of width or height given?
To narrow the topic usefully, this question only concerns itself with <!DOCTYPE html>
HTML5 documents.
I made a test page that shows this off in a few different HTML contexts, and only Firefox behaves the way I would expect (and prefer), inferring the one from the either, in all situations tested. In earlier testing, Chrome used to as well, but doesn't any more. Opera is very close.
One of the things I love about SVG is that the format lets you make images that render to whatever size of document you have, as long as you state which parts of the image should show (and optionally how it should be cropped), and not state just how large it should be drawn.
In effect, this lets you take a pretty logo, view and resize it at will in your browser, by just resizing your browser window to whatever size you want, and it happily draws to the new bounding box, without fuss.
This is accomplished by setting a viewBox
attribute on the <svg>
element, but neither the width
nor height
attributes, so it preserves that aspect ratio, with the (default) svg positioning and cropping strategy of preserveAspectRatio="xMidYMid meet"
, which essentially meens what background-position: 50% 50%; background-size: contain;
would mean for a CSS3 background image specification.
The preserveAspectRatio attribute indicates how an element with a viewBox providing a given aspect ratio must fit into a viewport with a different aspect ratio.
The quick way: img elementTo embed an SVG via an <img> element, you just need to reference it in the src attribute as you'd expect. You will need a height or a width attribute (or both if your SVG has no inherent aspect ratio). If you have not already done so, please read Images in HTML.
Note: object-fit works with SVG content, but the same effect can also be achieved by setting the preserveAspectRatio="" attribute in the SVG itself.
You want to look at http://www.w3.org/TR/CSS2/visudet.html#inline-replaced-width for the behavior that is required of browsers here. What CSS calls "intrinsic" refers to information of the image.
This behavior changed from a worse default not too long ago, so it is likely browsers still have issues in this area.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With