Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG images know their aspect ratio; why don't browsers respect it?

Tags:

html

svg

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.

Context and background of this question

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.

like image 311
ecmanaut Avatar asked Jun 03 '12 23:06

ecmanaut


People also ask

What is preserve aspect ratio?

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.

How to place SVG in HTML?

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.

Does object fit work with SVG?

Note: object-fit works with SVG content, but the same effect can also be achieved by setting the preserveAspectRatio="" attribute in the SVG itself.


1 Answers

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.

like image 152
Anne Avatar answered Oct 21 '22 11:10

Anne