javascript 如何在 div 容器中居中 svg
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34101825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to center a svg in a div container
提问by Mahtab Alam
I know this question have been asked multiple times on SO. I tried some of those answers but It didn't worked. What is the best way to center the svg element inside div
我知道这个问题在 SO 上被问过多次。我尝试了其中一些答案,但没有奏效。将 svg 元素置于 div 中的最佳方法是什么
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js" ></script>
</head>
<body>
<div id='canvas'></div>
<script>
var data = [10, 50, 80];
var r = 300;
var color = d3.scale.ordinal()
.range(['red', 'blue', 'orange']);
var canvas = d3.select('#canvas').append('svg')
.attr('width', 700)
.attr('height', 600);
var group = canvas.append('g')
.attr('transform', 'translate(300, 300)');
var arc = d3.svg.arc()
.innerRadius(200)
.outerRadius(r);
var pie = d3.layout.pie()
.value(function (d) {
return d;
});
var arcs = group.selectAll('.arc')
.data(pie(data))
.enter()
.append('g')
.attr('class', 'arc');
arcs.append('path')
.attr('d', arc)
.attr('fill', function (d) {
return color(d.data);
});
arcs.append('text')
.attr('transform', function (d) {
return 'translate(' + arc.centroid(d) + ')';
})
.attr('text-anchor', 'middle')
.attr('font-size', '1.5em')
.text(function (d) {
return d.data;
});
</script>
</body>
</html>
I want to put the donut chart in center
我想把圆环图放在中间
回答by Fawzan
You can add couple of css lines to the SVG element. You can inline it or have it in a separate style sheet. Just make sure it loads.
您可以向 SVG 元素添加几行 css 行。您可以将其内联或将其放在单独的样式表中。只要确保它加载。
svg{
display: block;
margin: auto;
}
This will align the SVG to the center of the div.
这将使 SVG 与 div 的中心对齐。
回答by Fasna
Just add centering style to your div.
只需为您的 div 添加居中样式即可。
<div id='canvas' style="text-align:center;"></div>
It will work.
它会起作用。