SVG container renders wrong size in Safari desktop

2020-08-16 17:05发布

问题:

I thought Safari had sorted this but it still seems to be an issue (unless I'm doing something obviously wrong).

I have a SVG placed inside an object tag. That is wrapped in a flexible containing DIV (e.g set to be width 50%). On resize, the container height resizes in Firefox, Chrome and Opera as I would expect but on Safari the container stays too high.

Here's an example on Codepen to demonstrate, switch to the full size result or 'editor on side' (button bottom right) to see the effect clearly in Safari: http://codepen.io/benfrain/full/fhyrD

Besides using JS to resize the SVG on load/resize, does anyone know if there is anything else I can do to make Safari behave correctly? Could of sworn I'd figured this out a few weeks back but now I seem to be hitting the issue again.

回答1:

So, Sérgio Lopez had an answer for this. You can employ the intrinsic ratio for video technique that Thierry Koblentz described here: http://alistapart.com/article/creating-intrinsic-ratios-for-video. More info at this blog post: http://benfra.in/20l

Here is the cut and paste code you need in your CSS:

Surrounding object tag

object {
    width: 100%;
    display: block;
    height: auto;
    position: relative;
    padding-top: 100%;
} 

And this for the SVG inside:

svg {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}