SVG Fit Text

by Scott Kaye

HTML

<div class="svg-fit-text">
    <svg>
        <text text-anchor="middle" x="50%" y="1.25em">$5,000,000,000</text>
    </svg>
</div>

<div class="svg-fit-text">
    <svg>
        <text text-anchor="middle" x="50%" y="1.25em">-$350,000</text>
    </svg>
</div>

<div class="svg-fit-text">
    <svg>
        <text text-anchor="middle" x="50%" y="1.25em" data-align="left">$500</text>
    </svg>
</div>

<div class="svg-fit-text">
    <svg>
        <text text-anchor="middle" x="50%" y="1.25em" data-align="right">$500</text>
    </svg>
</div>

SCSS

.svg-fit-text {
    width: 20%;
	height: 80px;
	padding: 10px;
	font-family: Varela Round;
	color: red;
	
	svg {
		width: 100%;
		height: 100%;

		text {
			font-size: 30px;
			fill: currentColor;
		}
	}
	
	border: 2px solid #999;
	box-sizing: border-box;
	display: inline-block;
}

JavaScript

// http://www.east5th.co/blog/2014/10/08/quest-for-scalable-svg-text/

// Delay is to show before/after
setTimeout(function() {

	$(".svg-fit-text svg").each(function() {
		var $text = $(this).find("text");
		
		$text.removeAttr("x");
		$text.removeAttr("y");
	
		var bbox = $text[0].getBBox();
		var viewBox = [bbox.x, bbox.y, bbox.width, bbox.height].join(" ");
		$(this).attr("viewBox", viewBox);

		var alignment = $text.data("align");
		if (alignment) {
			switch(alignment) {
				case "left":
					$(this).attr("preserveAspectRatio", "xMinYMid");
					break;
				case "right":
					$(this).attr("preserveAspectRatio", "xMaxYMid");
					break;
			}
		}
	});

}, 1000);