简体   繁体   English

HTML / CSS svg自动高度和宽度

[英]HTML/CSS svg auto height & width

Is there a way to make the svg automatically scale to the size of the circle inside it? 有没有一种方法可以使svg自动缩放到其内部圆圈的大小? Something like or something. 诸如此类的东西。 At the moment I give the svg a size, and the circle a size. 目前,我给svg一个尺寸,给圆一个尺寸。 Which causes them to not match (and I don't want to manually try and match both every time). 这导致它们不匹配(并且我不想每次都手动尝试匹配)。

See how the blue background is bigger than the circle. 查看蓝色背景如何大于圆圈。 I know I can just change the height and width, but it would be nice to have this change according to the circle size. 我知道我可以更改高度和宽度,但是最好根据圆的大小进行此更改。 I only want to change one element, not match both. 我只想更改一个元素,而不要两者都匹配。

 .divOrangeCircles { display: inline-block; background-color: aqua; opacity: 0.5; } 
 <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="css/styles.css"> </head> <body> <div class="divOrangeCircles"><svg height="200" width="200"><circle cx="90" cy="90" r="90" fill="#F48043"/></svg></div> </body> </html> 

What you want is the viewBox='xy width height' attribute, which will define the view-box of your SVG drawings. 您需要的是viewBox='xy width height'属性,该属性将定义SVG图纸的视图框。

SVG units are (generally) relative to their parent's box, by setting the viewBox attribute, you define how much of this units your SVG should display. SVG单位(通常)相对于其父级的框,通过设置viewBox属性,可以定义SVG应该显示多少单位。

 .divOrangeCircles { display: inline-block; background-color: aqua; opacity: 0.5; } svg { display: block; } 
 <div class="divOrangeCircles"> <svg viewBox="0 0 180 180" height="200" width="200"> <circle cx="90" cy="90" r="90" fill="#F48043"/> </svg> </div> 

Give your cx , cy and r should be in percentages in order to modify according to the Parent svg size. 给您的cxcyr应该以百分比为单位,以便根据父SVG大小进行修改。

Sample Fiddle 样品小提琴

For controlling sizes from css u can make svg height and width as 100% and give size from css. 为了从CSS控制尺寸,您可以将SVG高度和宽度设为100%,并从CSS给出尺寸。

<div class="divOrangeCircles"><svg height="100%" width="100%"><circle cx="50%" cy="50%" r="50%" fill="#F48043"/></svg></div>

Updated Fiddle 更新小提琴

  • Help :) 救命 :)

If you want to svg scale according to parent div then use this code. 如果要根据父div缩放比例,请使用此代码。 Don't be add manually dimensions in percentage. 请勿手动添加尺寸百分比。

.divOrangeCircles svg{
  width: 100%;
  height: 100%;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM