Cris
Cris

Reputation: 2021

Using D3 selection functions to properly align SVG in HTML layout

I'm playing around with D3 charts.

In my <body> tag I have:

<body>
  <div id="divs" style="margin-left: 5px; width: 100%;">
     <d1 style="float: left;"><big>Oil Consumption - Barrels (from 1965)</big></d1> <br><br>
     <d1 style="float: left;">BP Statistical Review of World Energy, June 2015</d1> <br><br>
     <div id="div"></div>
     <div id="div1" style="float: left;"></div>
  </div>
</body>

and in my Javascript code I have:

var svg = d3.select("body").append("svg").attr("width",700).attr("height",400);

The problem is that the d3.select("body") appends my svg chart vertically after the last div, while what I want to do is to align horizontally the svg with the div.

How can I do that?

This is the complete Plunkr -> Plunkr

UPDATE

I've tried as suggested by @Mark but it isn't working. This is the complete Plunkr -> Plunkr

var svg = d3.select("#divs")
                    .append("div")
                    .style("float","left")
                    .style("margin-left",400)
                    .style("width", "75%")
                    .append("svg")
                    .attr("width", 700)
                    .attr("height", 400);

Upvotes: 1

Views: 1107

Answers (1)

Mark
Mark

Reputation: 108537

If I'm understanding you correctly, you want your svg to be positioned to the right of the div with id of div1.

First, in order for this to work, just setting float: left on div1 isn't enough, it needs an explicit width in either % or px.

Second, you'll need to make your svg a child of the div with id of divs and wrap it in a div that is also floated with explicit width:

var svg = d3.select("#divs")
  .append("div")
  .style("float","left")
  .style("width", "75%")
  .append("svg")
  .attr("width", 700)
  .attr("height", 400);

UPDATE In order for your code to work I had to modify it to:

var svg = d3.select("#divs")
                .append("div")
                .style("margin-left", 400)
                .style("margin-top", 50)
                .style("width", "75%")
                .append("svg")
                .attr("width", 800)
                .attr("height", 300);

and the div to <div id="div1" style="float:left; width: 25%;"></div>

This is the result -> http://plnkr.co/edit/8lU9fjRHLQjP5xI2PCBf?p=preview

Upvotes: 1

Related Questions