html – 将方形svg放置在屏幕的中心,将其缩放以适应屏幕的宽度和
这似乎是一个愚蠢的问题,可能是一个笨蛋,但我找不到一个很好的解决方案,所以终于敢问.
我想放一个< svg>元素在html文档中,并满足以下要求: >图像被放置为< svg> html5元素,而不是外部的svg文件. (实际上,我想用D3.js动态生成它) 它基本上与this article中描述的要求相同.它表示我应该使用preserveAspectRatio =“xMidYMid”,但不提供如何做到这一点的例子,它如何对应于文章中描述的其他技巧. This article建议preserveAspectRatio =“xMidYMid meet”,但是我再也无法重现提供的示例来满足我的所有要求. 我当前的代码是这样的,但它不适合高度,并不垂直居中. .svg-container { height:100%; width:100%; max-height:15cm; max-width:15cm; margin: 0 auto; } <div class="svg-container"> <svg id="picture" preserveAspectRatio="xMidYMid meet" viewBox="0 0 100 100"> <circle cx=50 cy=50 r=50></circle> </svg> </div> 解决方法
如果SVG的宽高比是给定的,以下工作.如果SVG的宽高比是动态的,那么我必须使用JavaScript.
此代码段适用于现代浏览器,并充分利用相对较新的vmin viewport-percentage length.浏览器支持为pretty good.对于水平和垂直居中,可以利用flexbox布局模式.浏览器支持也是pretty good. 诀窍是SVG的尺寸相对于屏幕的宽度或高度设置,取其中最小者.这意味着即使我们将它设置为100vmin,SVG也可以保证适合屏幕(但几乎没有).为了实现最大尺寸,使用好的旧 html,body { /* ensure that all of the viewport is used */ width: 100%; height: 100%; /* ensure that no scrollbars appear */ margin: 0; padding: 0; /* center SVG horizontally and vertically */ display: flex; align-items: center; justify-content: center; } #picture { /* ensure 1:1 aspect ratio,tweak 50 to make SVG larger */ width: 50vmin; height: 50vmin; /* set some maximum size (width and height need to match * aspect ratio,1:1 in this case */ max-width: 200px; max-height: 200px; } <svg id="picture" viewBox="0 0 100 100"> <circle cx="50" cy="50" r="50"></circle> </svg> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |