Adjust the position of an SVG element based on its size using a transformation

How can I offset an SVG element relative to its own size using translate with a percentage, similar to how we would offset a div using transform: translate(100%,0)? Here is an example:

This code:

  <div style={{ overflow: 'visible', position: 'relative' }}>
    {/* rect */}
    <div style={{ height: 20, width: 20, background: 'black', position: 'absolute' }} />
    {/* circle */}
    <div
      style={{
        height: 20,
        width: 20,
        background: 'purple',
        borderRadius: '50%',
        position: 'absolute',
        transform: 'translate(100%,0)',
      }}
    />
  </div>

will look like this: https://i.sstatic.net/q4m0W.png. The circle offset is relative to its own size.

However, in this case:

<svg overflow={'visible'}>
  <rect width={20} height={20} />
  <circle cx={10} cy={10} r="10" fill="purple" style={{ transform: 'translate(100%,0px)' }} />
</svg>

the result will be different: https://i.sstatic.net/JpTAS.png.

The issue here is that the circle is being offset relative to the size of the svg canvas, which was never explicitly set: https://i.sstatic.net/KjgcM.png.

So, why does transform: 'translate(100%,0)' work relative to self in div html elements but relative to parent on SVG elements?

I have already tried wrapping g elements or svg elements as suggested in other answers, but no luck.

Instead of manually calculating dimensions using .getbBox() function and offsetting by pixels, I am looking for a simpler solution. Any ideas?

Demo

https://codesandbox.io/s/svg-vs-div-transform-translate-o2ii7

Answer №1

To ensure proper alignment, adjust the transform-box setting to fill-box. In React, remember to use camel case as shown below:

style={{ transform: "translate(100%,0px)", transformBox: "fill-box" }}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Difficulty with rendering content from Angular routes

Currently, I am working on a movie application where users can click on a details button to view information about a specific movie. However, I am facing an issue in displaying the information for the selected movie without showing all the movies at once. ...

Create a pop-up window within a single controller using Angular.js

I followed a tutorial to create this code. I am interested in learning how to utilize just one controller for generating the dialog box. Currently, I am using two controllers for this project. Any guidance or tips would be greatly appreciated. View my cod ...

How can markers be filtered on a Google Map API without the need to refresh the map?

I have created an Angular JS module that utilizes the Google Map API. The map is defined as a global variable, along with a global array for markers, and functions for managing these markers such as removing them, resetting the map, and adding new markers. ...

Incorporate a collection of product titles along with their short forms in JavaScript/jQuery

Seeking guidance as a newcomer to JS. I have encountered the need for two different views in an application I am working on - one displaying full product names and the other showing only their abbreviations. Instead of hard-coding this information, I wish ...

Using Javascript to extract a custom attribute from a button element

In my HTML, there is a button that has a custom property called data-filter-params: <button class="button" type="submit" data-filter-params="{'Type', 'Filter.Type'},{'Code','Filter.Code'}" >Filter</button&g ...

Can an element be visible on the page even if it doesn't have a defined height and width

I came across a piece of code in an existing Selenium automation framework that checks for the width and height of an element before determining if it is interactable. It seems like the element can only be clicked or double-clicked if both its width and he ...

How to position an element to the right in Bootstrap 4 without causing it to move to a new line immediately?

As a newcomer to Bootstrap, I have come across only one individual who has raised this issue before. Unfortunately, they did not receive a satisfactory solution, prompting me to bring up the question once more. My dilemma involves two button groups. When ...

outside vue component access method is not recommended

I am a newcomer to Vue.js and have implemented a comment feature similar to the one described here. However, due to certain constraints, I had to make adjustments. I used a Vue component but encountered an issue where it couldn't access a method insid ...

Issues arising post transitioning to 14.0.0 from 13.0.0 version of ngx-masonry library leading to failed tests

Following the update to the latest stable version of the library ngx-masonry 14.0.0, our tests started failing. The release was just yesterday (24.10.2022) and you can find the changelog here: https://github.com/wynfred/ngx-masonry/blob/master/CHANGELOG.md ...

Error thrown due to syntax issues in react.d.ts declaration file in TypeScript

Currently, I am attempting to integrate react with typescript in my project. However, typescript is generating syntax errors for the react.d.ts file sourced from Github: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/react The encountered ...

In both JavaScript and VB.NET, it is important to note that the expression does not yield a value

Within the Create View for the "Deal" model, I have implemented a JavaScript function that is intended to generate a new object within a List Property when a specific button is clicked. The error message "expression does not produce a value" has appeared. ...

Changing the Structure of a JSON Data Object

After using Papa Parse to generate a JSON from a CSV file, the structure of the JSON appears as follows: { object, object, object, .... , object } Now, I have a requirement to transform this JSON into the following format: { "publication" : { ...

Merge arrays of objects if they share at least one common property

// The following is an array that needs to be transformed const data = [ { name: 'shanu', label: 'ak', value: 1, }, { name: 'shanu', label: 'pk&ap ...

Unable to administer AuthenticationController

I am attempting to inject a controller into my app.run function, but I keep encountering the following error: Uncaught Error: [$injector:unpr] http://errors.angularjs.org/1.2.10/$injector/unpr?p0=AuthenticationControllerProvider%20%3C-%20AuthenticationCon ...

Issues arise when attempting to use custom Javascript functions in conjunction with the Bootstrap 4 Input Tagging Plugin

Currently, I am utilizing the Bootstrap tags input plugin to create tags within a text input on my HTML page. However, I am encountering difficulties in executing Javascript functions that should be activated when the input field is clicked while using thi ...

inserting a dynamic variable into a JSON string

My goal is to create a javascript object, var systemName = {"system" : varA}; However, I want the object to be structured like `{"system" :"varA"} where varA contains the variable value but is enclosed in double quotes. I attempted {"system" : "'+ ...

Creating redux reducers that rely on the state of other reducers

Working on a dynamic React/Redux application where users can add and interact with "widgets" in a 2D space, allowing for multiple selections at once. The current state tree outline is as follows... { widgets: { widget_1: { x: 100, y: 200 }, widg ...

Sending the handleSubmit() function to the child component does not alter the state of the parent component

I just started learning React and Javascript. Currently, I am working on a form where users can specify the details of a "Mob". Upon submitting the form, I anticipate that handleSubmit() (which is passed down from the parent component) will update the sta ...

Changing the color of a specific span using Angular

I am working with a dynamic mat-table where columns are added and populated on the fly. The table headers are styled using divs and spans. My goal is to change the color of a header to black when clicked, but also un-toggle any previously selected header. ...

Tips for disabling the default behavior by using preventDefault in JavaScript

I need help with removing the preventDefault() function and submitting the form in the else condition of my code. Does anyone know how to achieve this? if(email.val() != ""){ //check email e.preventDefault(); $.ajax({ ...