2016-05-15 104 views
-2

我想将标题添加到我的图中。 事情是这样的:CSS高度和宽度不适用于SVG

enter image description here

我已经试过append.svg,append.text ....等 但似乎没有任何工作。我,我只是不能够写这个我猜想 正确的CSS。这里

此代码:

header= d3.select("svg").append("text") 
    .attr("x", 70)    
    .attr("y", 20) 
    .style("font-size", "16px") 
    .style("text-decoration", "underline") 
    .text("My graph heading..."); 

,但我在这一个问题,因为我不能 分配给它的宽度和高度,背景填充。 当我分配它的宽度或高度它只是做,nt得到应用。 也在改变显示阻塞是不工作...

运行上面的代码,使得这样一个数字: 我现在的图形画面

enter image description here

+0

也许你可以用d3为它添加一个类/ ID,然后用纯CSS而不是用d3应用这些样式?和/或:如果更改显示屏阻止不起作用,我想知道是否可能没有特殊性问题,并且“!important”是否可能会强制它? –

+0

'svg'元素的行为与'html'元素不一样。尝试在代码中添加'.style('text-anchor','center')'。这是替代'文本对齐:中心'在css – iulian

+0

@iulian可能是正确的,我的评论可能误导/浪费时间。 :-) –

回答

0

试试这个:

d3.select('svg').append('rect') 
    .attr('x', 70) 
    .attr('y', 20) 
    .attr('width', 200) // <-- your width here 
    .attr('height', 100) // <-- your height here 
    .style('fill', 'red'); // <-- your color here 

d3.select('svg').append('text') 
    .attr('x', 170)  // <-- middle horizontal point of the rect (width/2 + leftMargin) 
    .attr('y', 70)  // <-- middle vertical point of the rect (height/2 + topMargin) 
    .attr('dy', '0.4em') // <-- tune this attribute to obtain perfect vertical alignment 
    .style('text-anchor', 'middle') // keep your text centered 
    .text('My graph heading...'); 

最后,您将获得:

enter image description here