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.