如果SVG的宽高比是给定的,以下工作.如果SVG的宽高比是动态的,那么我必须使用JavaScript.
此代码段适用于现代浏览器,并充分利用相对较新的vmin @L_301_3@.浏览器支持为pretty good.对于水平和垂直居中,可以利用flexbox布局模式.浏览器支持也是pretty good.
诀窍是SVG的尺寸相对于屏幕的宽度或高度设置,取其中最小者.这意味着即使我们将它设置为100vmin,SVG也可以保证适合屏幕(但几乎没有).为了实现最大尺寸,使用好的旧max-width和max-height,正如它们旨在使用的那样.
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;
}