【问题标题】:CSS height and width not applying to SVGCSS 高度和宽度不适用于 SVG
【发布时间】:2016-09-11 09:59:14
【问题描述】:

我想在我的图表中添加标题。 像这样的东西:

我试过 append.svg , append.text....等 但似乎没有任何效果。我只是无法为 我猜是这个。

这里的代码有效:

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

但是我在这方面有问题,因为我无法做到 为其分配宽度和高度以及背景填充。 当我为其分配宽度或高度时,它会被应用。 将显示更改为阻止也不起作用...

运行上面的代码会生成如下图: 我现在的图表图片

【问题讨论】:

  • 也许您可以使用 d3 为其添加一个类/ID,然后使用纯 CSS 而不是 d3 应用样式?和/或:如果将显示更改为阻止不起作用,我想知道是否可能没有特异性问题,!important 是否会强制执行?
  • svg 元素的行为与 html 元素不同。尝试将.style('text-anchor', 'center') 添加到您的代码中。这是 css 中 text-align: center 的替代方法
  • @iulian 可能是对的,我的评论可能具有误导性/浪费时间。 :-)
  • text-anchor: middle,不是中心
  • 好吧再次...我怎样才能让标题标签全宽,显示块和图形的一部分。

标签: javascript css d3.js svg


【解决方案1】:

试试这个:

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...');

最后,你会得到这个:

【讨论】:

    猜你喜欢
    • 2016-04-15
    • 2019-12-03
    • 2011-01-30
    • 1970-01-01
    • 2020-06-03
    • 2014-11-11
    • 2017-10-17
    • 2021-10-02
    • 1970-01-01
    相关资源
    最近更新 更多