score:2

Accepted answer

I would recommand to not append your SVG directly to the body element but to a wrapper div that you could style in CSS. (with flexbox properties if you also need vertical centering : http://philipwalton.github.io/solved-by-flexbox/demos/vertical-centering/)

score:0

You can either style the SVG directly or wrap the SVG in a div.

Method 1:

let svg = d3.select("body")
            .append("svg")
            .attr("width", wi + margin.right + margin.left)
            .attr("height", h)
            .style("background-color", "lightblue")
            .style("display", "block")
            .style("margin", "auto")

If you have lots of styling for the svg, it's preferable to assign a class to it and then define the class using CSS:

let svg = d3.select("body")
            .append("svg")
            .attr("width", wi + margin.right + margin.left)
            .attr("height", h)
            .attr("class", "svg-style")

and then

.svg-style {
        background-color: lightblue;
        display: block;
        margin: auto;
           }

Method 2:

Alternatively, as Delapouite suggested, you may wrap the svg within a div and then style the div (in CSS or directly):

<div id = "demo-div" style="text-align: center">
</div>

let svg = d3.select("#demo-div")
            .append("svg")
            .attr("width", wi + margin.right + margin.left)
            .attr("height", h)


Related Query

More Query from same tag