tsotsi tsotsi - 3 months ago 5
CSS Question

How to set position of the top svg element?

Let's say we've got a very simple set up like below

<html>
<head></head>

<body>
<script type="text/javascript">
var svg = d3.select("body").append("svg");
svg.attr("width", "100").attr("height", "100").style("border", "1px solid black");
</script>
</body>
</html>


What determines the position of the top svg element? How would it be possible to change it?

When you look up the attributes of an svg element you will find that it has got x and y attributes, but in both cases it says that


Has no meaning or effect on outermost svg elements


It makes sense though because x and y would only be defined relative to the parent svg element. How to set the position of the top on then?

Thanks!

Answer

You can position the outermost element just like any other DOM element.

var svg = d3.select("body").append("svg");
svg.attr("width", "100").attr("height", "100").style("border", "1px solid black");
svg {
  position: relative;
  top: 100px;
  left: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>