-1

Here is my code. Could you guide me how to align the paragraph in the center of rectangle using both css and d3.js.

Also why is there a space at the start of paragraph. Should the paragraph not start from the rectangle's y position?

let svg = d3
  .select("body")
  .append("svg")
  .attr("width", 1000)
  .attr("height", 1000);

let text = [
  "WHO Coronavirus disease situation dashboard presents official daily counts of COVID-19",
  "Data Analysis",
  "Javascript",
  "Compare Performance of S&P 500 Index against other Indices"
];

let rect = svg.selectAll("rect")
  .data([0, 150, 300, 450])
  .enter()
  .append("rect")
  .attr("width", (d, i) => 200)
  .attr("height", 150)
  .attr("x", (d, i) => 0)
  .attr("y", d => d)
  .attr("fill", "grey")
  .attr("stroke", "black")

let texty = svg
  .selectAll("boxestext")
  .data([0, 150, 300, 450])
  .enter()
  .append("foreignObject")
  .attr("width", (d, i) => 200)
  .attr("height", 150)
  .attr("x", (d, i) => 0)
  .attr("y", d => d)
  .attr("class", "boxes")
  .append("xhtml:body")
  .attr("class", "mytext")
  .attr("id", (d, i) => "mytext" + i)
  .style("font", 50)
  .html((d, i) => "<p>" + text[i] + "</p>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.5.0/d3.min.js" integrity="sha512-0XfwGD1nxplHpehcSVI7lY+m/5L37PNHDt+DOc7aLFckwPXjnjeA1oeNbru7YeI4VLs9i+ADnnHEhP69C9CqTA==" crossorigin="anonymous"></script>
pilchard
  • 12,414
  • 5
  • 11
  • 23
Zubair
  • 119
  • 8

1 Answers1

1

The space is probably due to margin. You can change that in css by declaring element's margin 0.

element {
    margin: 0;
}

The best way i've come to center elements in css is:

.className {
    position: absolute;
    transform: translate(-50%, -50%);
    left: 50%;
    top: 50%;
}

You can set <p class="classname"></p> or in the css file instead of .className refer to p, but this will apply to all your paragraphs. Note that transform: translate changes the reference point of your element from top left to (in this example) center. Therefore your element may overflow from the left which can't be viewed with scroll

tito
  • 60
  • 1
  • 9