SVG: Altering the dy attribute has no impact on the overall height of the bounding rectangle for the parent text

We are striving to align a group of tspan elements both vertically and horizontally.

However, the parent container is not taking into consideration dy values.

This lack of consideration is leading to alignment issues.

If you adjust the dy values in this Codepen example, you'll notice that the height of the text container remains constant: https://codepen.io/anon/pen/WLpvrG?editors=1111.

How can we accurately determine the bounding rectangle for tspan elements?

<svg id="textBox1" class="textBox" x="0%" y="0%" width="100%" height="25%">
  <rect class="background" x="0%" y="0%" width="100%" height="100%" fill="gray" fill-opacity="0.5" />
  <text class="tspanGroup" x="0" y="0"><tspan x="50%" dy="0em" text-anchor="middle">tspan line 0</tspan><tspan x="50%" dy="1.5em" text-anchor="middle">tspan line 1</tspan><tspan x="50%" dy="1.5em" text-anchor="middle">tspan line 2</tspan></text>
</svg>

Answer №1

The dy attribute signifies a shift vertically along the y-axis, rather than a resizing effect. Adjusting this value on the initial <tspan> element will result in vertical movement only, without altering the size of the container.

If you aim to center the text both vertically and horizontally, I recommend referring to the second response in this discussion: How to place and center text in an SVG rectangle. There's no need for me to duplicate that content here!

It took some effort to make it function correctly, but here is the tweaked code:

// Ensure the document is loaded to prevent undefined elements
document.addEventListener("DOMContentLoaded", function(event) {
// Center the text
centerText();

setTimeout(function() {
// Adjust font sizes
document.getElementById('size1').style.fontSize = "12px";
document.getElementById('size2').style.fontSize = "16px";
document.getElementById('size3').style.fontSize = "20px";

// Recenter the text
centerText();
}, 3000);
});

function centerText(){
// Retrieve the necessary elements
const container = document.getElementById('textBox1');
const textEle = document.getElementById('txt');

// Utilize getBBox for SVG element data
const cBox = container.getBBox();
const tBox = textEle.getBBox();

// Capture width and height of container SVG
const contHeight = cBox.height;
const contWidth = cBox.width;

// Determine size of TEXT element
const txtHeight = tBox.height;
const txtWidth = tBox.width;

// Adjust attributes to center text properly
textEle.setAttribute("x", (contWidth/2)-(txtWidth/2));
textEle.setAttribute("y", (contHeight/2)-(txtHeight/2));
}
<svg id="rootBox" width="375" height="812" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<svg id="textBox1" class="textBox" x="0" y="0" width="100%" height="25%">
<rect class="background" x="0%" y="0%" width="100%" height="100%" fill="gray" fill-opacity="0.5" />
<text class="tspanGroup" x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" id="txt">
<tspan x="50%" dy="0em" id="size1">tspan line 0</tspan>
<tspan x="50%" dy="1.5em" id="size2">tspan line 1</tspan>
<tspan x="50%" dy="1.5em" id="size3">tspan line 2</tspan>
</text>
</svg>
</svg>

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

I'm looking for an easy way to generate a special effect when my mouse interacts with a div using HTML, CSS, or JavaScript

I'm attempting to replicate this interesting effect where a div is surrounded by a container when the mouse hovers over it. It looks pretty cool, like in this image here: https://i.stack.imgur.com/p0epq.png Does anyone have any suggestions on how I ...

The functionality for accessing objects in Chrome Developer Tools is not functioning properly

Every time I attempt to access an object in Chrome Developer Tools, I encounter the following error message: VM4939:1 Uncaught TypeError: Cannot read property 'cells' of undefined at :1:13 Here is my code: <head> <script> ...

Retrieve the hidden input values from a div using jQuery

Currently, I am in the midst of a project using CakePHP with jQuery and AJAX. Within this project, I have a div that is being repeated in a PHP loop. Here is what the div looks like: <div class="heart"> <input type="hidden" i ...

The relative link feature in React Router fails to properly navigate

Currently, I am utilizing the npm package react-router-relative (https://www.npmjs.com/package/react-router-relative) for my project. However, it seems to be having trouble properly switching the URL. Here is how my links are configured: <Link to=&apo ...

What is the proper way to address the issue of nesting ternary expressions when it comes to conditionally rendering components?

When using the code below, eslint detects errors: {authModal.mode === 'login' ? <Login /> : authModal.mode === 'register' ? <SignUp /> : <ForgotPassword />} Error: Avoid nesting ternary expressions. eslint(no-nested-t ...

Show information in a text field from JSON in SAPUI5

How can I populate a text box with data from JSON using SAPUI5? // Sample JSON data var data = { firstName: "John", lastName: "Doe", birthday: {day:01,month:05,year:1982}, address:[{city:"Heidelberg"}], enabled: true }; // Create a JS ...

Incorporating Angular to dynamically fetch data through AJAX and fill in content post-page render

As a backend API developer diving into AngularJS (version 1) for the first time with my current project, I have encountered a scenario that requires me to fetch server-side content dynamically post-render. The page is set up with ng-app="app" in the <ht ...

Why does React-Perfect-Scrollbar not work properly when the height of an element is not specified in pixels?

Currently, I am developing a chat application with React 18 for its user interface. The app includes a sidebar that displays user profiles. To ensure the app fits within the browser window height, I've made the list of user profiles scrollable when n ...

Modify the background color of a div by selecting a hex code from a dropdown menu

Is there a way to utilize jQuery in order to alter the background of a <div> by choosing the HEX code from a separate dropdown menu? HTML <select id="target"> <option value="#c2c2c2">Grey</option> <option value="blue">Bl ...

Simple method to modify the text size of the entire HTML page

Looking for a way to adjust the font size of an entire HTML document? I'd like to have two buttons - one to increase the font size and the other to decrease it. Each button will trigger a JavaScript function; function increaseFontSize(){ //Increase ...

Learn the process of generating sequential heading numbers for topic headings in each HTML document using DTA or XHTML

I attempted to include hierarchical numbers for topic headings in dita2xhtml_eclipsehelp.xsl. (DITA OT HTML output) However, I am facing difficulty in producing numbers similar to the following in each html file: 1 heading text 1.1 heading text 1.1.1 Head ...

Utilizing the hcSticky plugin for creating a scrolling effect on webpage content

I'm attempting to utilize the JQuery plugin, hcSticky, in order to achieve a scrolling effect on my fixed content. However, I seem to be encountering some difficulty getting it to function properly. What could I possibly be doing incorrectly? JSFIDDL ...

How come TinyMCE is showing HTML code instead of formatted text?

I have been working on integrating TinyMCE with React on the frontend and django(DRF) on the backend. After saving data from TinyMCE, it retains the HTML tags when displayed back, like this: <p>test</p> <div>Test inside div</div> ...

What is a method to position an <img> on top of text without obscuring the text or resorting to CSS background or text-indent

To view the related code snippet, click on this link: http://jsfiddle.net/Ws8ux/ Is there a way to position the text under the logo without hiding it through display:none or text-indent? I am aiming to bring the image up while keeping the logo in the back ...

A PHP drop-down menu maintains a fixed position

I have set up a database called pogoda with a city table containing columns for city and cityid. Using PHP, I am creating a dynamic list and submitting the chosen value into subsequent code. To ensure that the drop-down list has a default starting positio ...

"Enhance your website with a unique Bootstrap 5 carousel featuring multiple

As a beginner in Bootstrap, I am currently working on an ecommerce template to learn about Bootstrap 5. I am interested in creating a carousel that displays multiple slides at once, like a products slider with left and right arrows. Is this possible in Bo ...

The API response indicates that the service is currently not accessible

I'm attempting to retrieve a report from the MOZ API, but I keep receiving this response: { "status" : "503", "error_message" : "Service Temporarily Unavailable" } This is the code I am using: function MozCall(callback) { var mozCall = ' ...

Effortlessly adjust the top margin of the div element

I have been attempting to smoothly move a div (circle), but I'm facing difficulties. The div instantly jumps to the final position instead of moving smoothly. In an effort to simulate the process of a ball falling, I tried using the animate method wi ...

My CSS is giving me a bit of trouble with alignment

I have been experimenting with various approaches such as adjusting the size of the divs to tiny dimensions and trying out inline-block or float left and right properties, but I am still unable to achieve the desired result of having my divs positioned s ...

How can I adjust the positioning of labels in Semantic UI React?

Has anyone successfully changed the label position from right side to left? I attempted using float: left but it didn't have any effect. import {Radio } from "semantic-ui-react" <Radio label="in progress" toggle /> https://i.sstatic.net/hNGb6. ...