Center text inside a d3 svg element

As a newcomer to the d3 library, I am facing challenges with a basic task.

Inspired by this example on gradients, I have integrated a linear gradient into the footer div element:

    #footer {
      position: absolute;
      z-index: 10;
      bottom: 10px;
      left: 50%;
      width: 300px;
      margin-left: -150px;
      height: 20px;
      border: 2px solid black;
      background: rgba(12, 12, 12, 0.8);
      color: #eee;
    }

var svg = d3.select("footer")
    .append("svg:svg")
    .attr("width", 300)//canvasWidth)
    .attr("height", 20);

svg.append("rect")
    .attr("width", 300)
    .attr("height", 20)
    .style("fill", "url(#linear-gradient)");

var defs = svg.append("defs");


var linearGradient = defs.append("linearGradient")
    .attr("id", "linear-gradient");

linearGradient.append("stop")
.attr("offset", "0%")
.attr("stop-color", "#ffa474"); 

linearGradient.append("stop")
    .attr("offset", "100%")
    .attr("stop-color", "#8b0000");

https://i.sstatic.net/xP8pw.png

I'm struggling with placing text "a" and "b" within the gradient bar, aligned to the left and right sides, above the colors. Adding text in the div element seems to displace the gradient bar instead of overlaying it.

Answer №1

To adjust the position of your text elements, you can utilize the text-anchor property. Specify "start" for the first text and "end" for the last one:

svg.append("text")
    .attr("text-anchor", "start")
    .attr("x", 4) // padding of 4px
    .attr("y", 14)
    .text("a");

svg.append("text")
    .attr("text-anchor", "end")
    .attr("x", 296) // padding of 4px
    .attr("y", 14)
    .text("b");

Check out this demonstration:

var svg = d3.select("#footer")
    .append("svg:svg")
    .attr("width", 300) // canvas width
    .attr("height", 20);

var defs = svg.append("defs");

var linearGradient = defs.append("linearGradient")
    .attr("id", "linear-gradient");

linearGradient.append("stop")
.attr("offset", "0%")
.attr("stop-color", "#ffa474"); 

linearGradient.append("stop")
    .attr("offset", "100%")
    .attr("stop-color", "#8b0000");

svg.append("rect")
    .attr("width", 300)
    .attr("height", 20)
    .style("fill", "url(#linear-gradient)");

svg.append("text")
.attr("text-anchor", "start")
.attr("x", 4)
.attr("y", 14)
.text("a");

svg.append("text")
.attr("text-anchor", "end")
.attr("x", 296)
.attr("y", 14)
.text("b");
#footer {
      position: absolute;
      z-index: 10;
      bottom: 10px;
      left: 50%;
      width: 300px;
      margin-left: -150px;
      height: 20px;
      border: 2px solid black;
      background: rgba(12, 12, 12, 0.8);
      color: #eee;
    }
<script src="https://d3js.org/d3.v4.min.js"></script>
<div id="footer"></div>

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

The jQuery find and replace feature is causing my entire content to be replaced instead of just specific paragraphs

Within this section, there are multiple paragraphs and an input field. The concept is simple: the user inputs text into the box, then hits "ENTER" to trigger a jquery function below. The process involves identifying matches between the paragraph content a ...

Please request user input in order to generate a multiplication chart

Is there a way to ensure that the program works properly so that when the user inputs a value, it is included in the multiplication table? <html> <head> <title> Multiplication Table </title> <style> body{ font-family: aria ...

Utilize Wordpress TinyMCE to apply the underline decoration using the "U" tag instead of the style

Is there a way to modify the function of the button in the WordPress content textarea of TinyMCE? Specifically, I am referring to the "u" button for underline formatting. <span style="text-decoration-line: underline;">text underlined</span> I ...

What is the process for editing or importing CSS within a React project?

I'm a beginner in React and I am encountering an issue with CSS not loading properly. I followed the tutorial for importing it, but it seems like there might be a better way to do it now as the tutorial is outdated. Below is my code, I would appreciat ...

What is the best way to ensure a textarea remains expanded when the parent element is in focus?

I have successfully implemented a textarea box that expands upon click and retracts when it loses focus. However, I am facing an issue where if the textbox is already in expanded form, I want it to stay expanded if the user clicks anywhere within the cont ...

The issue of jQuery's .last() function triggering multiple times with just a single click on the last

I currently have a set of tabs containing radio buttons and I need to trigger an event when the last option is selected (meaning any radio button within the final tab, not just the last radio button). Below is the HTML code: <div id="smartwizard" clas ...

Concealing Vimeo's controls and substituting them with a play/pause toggle button

I'm currently working on implementing the techniques demonstrated in this tutorial (), but unfortunately the code in the fiddle I put together doesn't appear to be functioning correctly. I'm at a loss as to what might be causing this issue. ...

Enhancing jQuery functionality: Ensuring newly added elements are aware of existing functions

I need assistance with my HTML table. Each row (tr) contains a value, for example 200$, and a delete button. How can I ensure that each new row added automatically knows the recent functions without having to call them every time? $(function () { $(&ap ...

Rearrange items in a display: contents wrapper using CSS Grid

I'm having trouble positioning descendants in a root grid while they are enclosed in a container with display: contents. The issue I am facing is that one element is not being correctly placed within the grid: .wrapper { width: 80ch; margin: a ...

Is it possible to incorporate vector graphics/icons by simply adding a class to a span element in HTML5?

In order to add a glyphicon icon to our webpage, we simply need to include its class within a span element, as demonstrated here: <span class="glyphicon glyphicon-search"></span> We also have a few files in .ai format that can be converted to ...

What could be causing the unresponsive hamburger button on my navbar?

As a beginner in HTML and Flask, I am attempting to create a navbar. However, I am encountering an issue with the hamburger button not functioning properly. When I resize the window smaller, the hamburger button appears but does not show the items like "Lo ...

Is it necessary to number each header and paragraph when coding in HTML?

Do I need to write paragraphs as p1, p2, and p3 when using headers like h1, h2, and h3, or can I simply use p? Additionally, which text editor app is recommended for a Macbook? ...

Designing an image transformation page by segmenting the image into fragments

Does anyone have insight into the creation process of websites like this one? Are there any plugins or tools that can assist in building something similar? ...

Adding query parameters to the end of every link on a webpage

Wondering how to automatically add GET values to the end of each anchor href on a webpage? For instance, if you input google.com?label=12&id=12 I want to ensure that "?label=12&id=12" gets added to the end of every single href in an anchor tag on ...

Struggling to decide on the perfect CSS selector for my puppeteer script

I am trying to use puppeteer page.type with a CSS selector. <div class="preloader"> <div class="cssload-speeding-wheel"></div> </div> <section id="wrapper" class="login-register"> <div class="login-box"> <d ...

Applying inline styles in PHP using if/else conditions

I want to customize the appearance of my table based on the status of each entry. Specifically, Completed = Green & Pending = Orange This involves PHP code that retrieves data from a MySQL database. $query = mysql_query("SELECT * FROM cashouts WH ...

CSS: Aligning content vertically centered

Take a look at the following example: <div class="container"> <div class="box1"></div> <div class="box2"></div> </div> The height of box1 is smaller than that of box2. Is there a way to vertically center box1 w ...

Creating a visually striking layout with Bootstrap card columns masonry effect by seamlessly adjusting card heights to prevent any

When using the bootstrap card columns masonry and a user clicks on a button inside a card, the height of the card changes dynamically by adding a card-footer. However, in certain situations, the cards change position causing a jumpy effect. To see this i ...

Attempting to implement Ajax for my AddToCart feature while iterating through a form

At the moment, I am facing an issue where only the first item is being added to the cart and the page remains unchanged. On each page, there are a minimum of 3 items, with a new form created for each one. However, the other products do not get added to the ...

Customizing meter-bar for Mozilla and Safari

I've implemented the following CSS on my meter bars but for some reason, the styling isn't showing up correctly in Safari (refer to the screenshots below). I'm relatively new to CSS and simply copied the code provided. Based on the comments, ...