JSFiddle - React, Tailwind, and code Playground

by Henry

HTML

<div id="container"></div>

CSS

#container {
    height: 50px;
    width: 400px;
    border: 1px solid red;
}

text {
    text-anchor: end;
}

JavaScript

var text = 'Foobarfoo';
//var textWidth = 50; //how to calculate this?
var plotWidth = 400;
//var barWidth = plotWidth-textWidth;

var plot = d3.select(container)
            .insert("svg")
            .attr('width', plotWidth)
            .attr('height', 50);

plot.append("text")
    .attr("x", plotWidth)
    .attr("y", 28)
    .text(text)

var text_element = plot.select("text");

var textWidth = text_element.node().getComputedTextLength()

var barWidth = plotWidth-textWidth;

plot.append("rect")
    .style("fill", "steelblue")
    .attr("x", 0)
    .attr("width", barWidth)
    .attr("y", 0)
    .attr("height", 50);