I'm using D3.js
. I'd like to find an SVG equivalent to this CSS class, which adds ellipses if text flows out of its containing div:
.ai-ellipsis { display: block; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; -o-text-overflow: ellipsis; -moz-binding: url(<q>assets/xml/ellipsis.xml#ellipsis</q>); }
This is my SVG:
<g class="bar" transform="translate(0,39)"> <text class="label" x="-3" y="6.5" dy=".35em" text-anchor="start">Construction</text> <rect height="13" width="123"></rect> </g>
It's generated as follows:
barEnter.append("text").attr("class", "label") .attr("x", -3).attr("y", function() { return y.rangeBand() / 2}) .attr("dy", ".35em").attr("text-anchor", "start") .text(function(d) { return d.Name; });
Currently the text is overflowing and overlapping the rect element.
Is there any way I can say "if text is more than a certain width, crop it and add ellipses"?
To clip at the transition between characters you can specify text-overflow as an empty string, if that is supported in your target browsers: text-overflow: ''; . This keyword value will display an ellipsis ( '…' , U+2026 HORIZONTAL ELLIPSIS ) to represent clipped text.
The text-overflow property specifies how overflowed content that is not displayed should be signaled to the user. It can be clipped, display an ellipsis (...), or display a custom string.
text-overflow: ellipsis only works when the following is true: Parent element is not set to display: inline (span's default,) You must use display: block or display: inline-block. The element's width must be constrained in px (pixels) – it doesn't work with values specified using % (percent.)
The overflowing content can be clipped, display an ellipsis ('…'), or display a custom string. Syntax: text-overflow: clip|string|ellipsis|initial|inherit; Property Values: All the properties are described well with the example below.
a wrapper function for overflowing text:
function wrap() { var self = d3.select(this), textLength = self.node().getComputedTextLength(), text = self.text(); while (textLength > (width - 2 * padding) && text.length > 0) { text = text.slice(0, -1); self.text(text + '...'); textLength = self.node().getComputedTextLength(); } }
usage:
text.append('tspan').text(function(d) { return d.name; }).each(wrap);
I am not aware of an equivalent CSS class for SVG, but you can use foreignObject
to embed HTML in SVG. This gives you access to this functionality and is more flexible in general (e.g. you can do automatic line breaking easily).
See here for a complete example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With