Home > OS >  Html position svg image with variable height
Html position svg image with variable height

Time:06-26

I want to place an image to a position.

<svg width="100%" height="100%">
     <image x="100" y="100" width="50" href="..."></image>
     ... other elements
</svg>

The origin of an image is the top left corner, thus images are placed like the red on in the example below. However, I want the bottom center to be at that position. The width is fix, so I can easly retrieve half of it to the x coordinate, having the image horizontaly aligned. But the height can vary. I tried

transform: translate(0, -100%)

But this result in translating 100% of the parent svg height, and not it own height. I'm thinking about opening the file and reading it height, but it is quite expensive. Is there other solutions ?

Example Actual result (Red) and goal (Green)

CodePudding user response:

Add transform-box: fill-box; as a CSS property to the image.

<svg width="100%" height="100%">
     <style>
        image {
          transform-box: fill-box;
        }
     </style>
     <image x="100" y="100" width="50" href="..."></image>
     ... other elements
</svg>

That changes the transfom co-ordinate system from the default viewBox (view-box as a CSS value) to the bounding box of the image which would appear to be what you want. Once you do that, translate percentages will work as you wish them to.

  • Related