Resizing single shapes dynamically without scaling the whole SVG

后端 未结 5 1142
悲&欢浪女
悲&欢浪女 2021-02-01 22:58

I have an arrow as a SVG which\'s length I want to alter in response to the width of a wrapping DIV (for example).

All my previous attempts have led into this behavior (

5条回答
  •  天命终不由人
    2021-02-01 23:41

    Yes, you can use percentages in svg.

    for basic shapes its quite simple. You can write your main rect as

    
    

    your second rect is even simpler, as it sits at 0,0 all the time

    
    

    but with the arrow there is a problem in pathes and polygon you can not use percentages. To work around this problem there is a two step solution.

    first put the path in a symbol element:

    
      
    
    

    now you can position this symbol like you would position a rect... easy...

    
    

    but now your arrow starts a 100% and is completely outside of your viewport. you could just set overflow: visible on your svg and be done with it, but that is not what we want... we want the arrow to end at 100%. But that easy as well, we know that the arrow is 20px wide. So just translate the use back 20px:

    
    

    using this approach, you can position any shape at any position base on percentages...

    to warp it all up, your complete svg now looks like this:

    
      
        
      
      
        
        
        
      
    
    

    and here is a snippet using this svg with 3 different widths:

    svg:nth-of-type(1) {
      width: 100px
    }
    svg:nth-of-type(2) {
      width: 200px
    }
    svg:nth-of-type(3) {
      width: 300px
    }
    
      
        
      
      
        
        
        
      
    
    

提交回复
热议问题