Positioning SVG elements using CSS

后端 未结 7 1885
野性不改
野性不改 2020-12-29 01:14

Assume the following svg document:




        
7条回答
  •  有刺的猬
    2020-12-29 01:58

    Here is a hacky possibility to position specifically text-elements purely by CSS, by abusing the attributes ‘letter-spacing’ for the x-coordinate and ‘baseline-shift’ for the y-coordinate:

    
        
            
        
        
    
    .CSS-Positioned Text!
    

    ‘baseline-shift’ is only applicable on ‘tspan’ Elements, thus making the inner necessary in the presented code. Positive values for baseline-shift move the text upwards, opposite of the normal direction in the svg.

    ‘letter-spacing’ needs an initial letter to have an effect, thus making the . necessary. To eliminate the width of this first letter, we use the special made font cssPosAnchor, where the dot has no width and no shape. The following additionally restores font and letter-spacing.

    Scope

    Should work in every conforming SVG implementation.

    There is one indefinite limitation though for negative x-coordinates. The specification for the ‘letter-spacing’ attribute says: “Values may be negative, but there may be implementation-specific limits.”

    Compatibility

    Text ‘direction’ change should work just fine, when imposed on the inner .

    A non-standard ‘writing-mode’ must be imposed on the outer . There will most certainly be problems with that.

    The probably more important ‘text-anchor’ values middle and end can be made possible like this:

    
        
            
            
        
        
    
    .CSS-Positioned Text! .
    

    The ‹space›. before the closing <\text> tag produces spacing equal to minus x-coordinate. So the inner is moved around but preserves it's space in the as if it was still there.

    Since there may be implementation-specific limits on negative values for the spacing attributes, this is not guaranteed to work on all clients!

提交回复
热议问题