How can I create dynamic letter spacing for a line of text that starts with 100% width of a container and reduces as the screen size gets smaller? I want the letter spacing to adjust based on the container’s width, and the text’s width should be recalculated whenever the window is resized.
I am getting letter spacing but not the width of the container.
$(document).ready(function () {
function adjustLetterSpacing() {
var containerWidth = $(".container").width();
var textElement = $(".dynamic-text");
var maxWidth = containerWidth - 50;
var textWidth = textElement.width();
var letterSpacingValue = 0;
if (maxWidth > textWidth) {
var textLength = textElement.text().length;
letterSpacingValue = (maxWidth - textWidth) / (textLength - 1);
}
$(".dynamic-text").css("letter-spacing", Math.max(0, letterSpacingValue) + "px");
}
// Initial adjustment on page load
adjustLetterSpacing();
$(window).on("resize", adjustLetterSpacing);
});
.container {
width: 1200px;
}
.dynamic-text {
white-space: nowrap;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
<p>
<span class="dynamic-text">
Lorem ipsum dolor sit amet
</span>
</p>
</div>
Any guidance on how to implement this effect would be appreciated.
2
Answers
You could do something like this with Vanilla JS.
We add a "hidden/interim" element to the document with the text, grab it’s width.
We could grab that the first time and cache it if we wanted.
Then we just figure out what the letter spacing needs to be based on the overall width minus the texts original width.
We can just make the span as wide as the div. and give the letter spacing as width/totalLetters.
But at very first we will also store the actual width of the letters because there are words too with spaces.