简体   繁体   中英

How do I center a <svg> in <body> based on screen width/height

I did some research on the matter, but it doesn't seem to be working.

I want to be able to make a <svg> container that encompasses the entire screen of the browser (aka everything that isn't a tab, toolbar, etc. etc.).

这是一张照片

So if you look at the picture, I want the <svg> to occupy everything below the tab toolbar to the bottom of the page (is it the viewport or window?)—aka everything in the red box.

Here's the code I have so far (just the <script /> ):

<script>
function startThePage(){
  var height = $(document).height();
  var width  = $(document).width();

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

  var myCircle = svgSelection
      .append("circle")
      .attr("cx", (width/2))
      .attr("cy", (height/2))
      .attr("r", 22)
      .style("fill", "lightgray")
      .style("stroke", "gray");

};
//alert(window.screen.availWidth);
//alert(window.screen.availHeight);

</script>

For some reason this seems to make the document slightly bigger, meaning the user can scroll back and forth (for now there's just a filler circle in it, which I want to center). This puts the circle out of center. How do I fix that?

I think box-sizing:border-box , margin:0;padding:0; , and overflow:hidden should cover mostly everything...

In order to manipulate the circle, i think you need to play with the

.attr("cx", (width/2))
.attr("cy", (height/2))

values and as far as raising the cx value to be approx half of the screen width. Then you can set the cy value to approx 20 or so. Hope that helps.

In order to center your circle on the x-axis, you have to set the margin-right:auto; and margin-left:auto; That will center your circle on the x-axis. As for your <svg> , make sure the html and body elements have the following attributes:

html, body {
    width:100%;
    height:100%;
    margin:0px;
    padding:0px;
}

Then make sure your <svg> has the following attributes:

svg {
    width:100%;
    height:100%;
    margin:0px;
    padding:0px;
}

That should center your circle and properly fill the <svg> to the entire screen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM