Jans
Jans

Reputation: 35

Making svg container appear one below another on array looping

I have the following code where I created two svg container of different height and width and it is created for every element in the array. The code works well but I want the svg container text1 which contains title1 to appear below the svg container text2 that displays the title2 rather than side by side that's how it appears now, i.e., next to each other. How to make container 2 to appear just below the container 1

Here is the code

function draw(data) {
    data.forEach(function(d) {
        var text1 = d3.select("body").append("svg")
            .attr("width", 200)
            .attr("height", 100);

        var title1 = d.values.title1;

        text1.append("text")
            .attr("x", "50%")
            .attr("y", "10%")
            .text(title1);

        var text2 = d3.select("body").append("svg")
            .attr("width", 300)
            .attr("height", 500);

        var title2 = d.values.title2;

        text2.append("text")
            .attr("x", "40%")
            .attr("y", "10%")
            .text(title2);
    });
}

Upvotes: 2

Views: 1102

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

You probably can solve your problems just changing your CSS. By default, SVGs will display side by side, if there is enough room in the page. In this snippet, 5 SVGs are produced (click "run code snippet"):

var data = d3.range(5);

var body = d3.select("body");

var svg = body.selectAll("svg")
  .data(data)
  .enter()
  .append("svg")
  .attr("width", 100)
  .attr("height", 100);
svg {
  background-color: teal;
  margin-right: 5px;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

This is exactly the same code, but setting the display in the CSS:

  display: block;

Check the difference (click "run code snippet"):

var data = d3.range(5);

var body = d3.select("body");

var svg = body.selectAll("svg")
  .data(data)
  .enter()
  .append("svg")
  .attr("width", 100)
  .attr("height", 100);
svg {
  background-color: teal;
  display: block;
  margin-bottom: 5px;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Upvotes: 3

Related Questions