[英]How do I center a <svg> in <body> based on screen width/height
我對此事做了一些研究 ,但似乎沒有用。
我希望能夠制作一個<svg>
容器,該容器包含瀏覽器的整個屏幕(也就是不是選項卡,工具欄等的所有內容)。
因此,如果您查看圖片,我希望<svg>
占據頁面底部選項卡工具欄下方的所有內容(是視口還是窗口?),也就是紅色框中的所有內容。
這是我到目前為止的代碼(只是<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>
由於某種原因,這似乎會使文檔稍大一些,這意味着用戶可以來回滾動(現在,其中只有一個填充圓圈,我想居中)。 這會使圓偏離中心。 我該如何解決?
我認為box-sizing:border-box
, margin:0;padding:0;
,並且overflow:hidden
應該幾乎涵蓋了所有內容...
為了操縱圈子,我認為您需要玩
.attr("cx", (width/2))
.attr("cy", (height/2))
值,以及將cx值提高到屏幕寬度的一半左右。 然后,您可以將cy值設置為大約20左右。 希望能有所幫助。
為了使圓在x軸上居中,必須設置margin-right:auto;
和margin-left:auto;
那將使您的圓在x軸上居中。 至於<svg>
,請確保html和body元素具有以下屬性:
html, body {
width:100%;
height:100%;
margin:0px;
padding:0px;
}
然后,確保您的<svg>
具有以下屬性:
svg {
width:100%;
height:100%;
margin:0px;
padding:0px;
}
那應該使圓心居中,並正確地將<svg>
填滿整個屏幕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.