Skip to content

Instantly share code, notes, and snippets.

@nigjo
Last active September 6, 2020 14:05
Show Gist options
  • Save nigjo/906578fa4cecd80f9c84e1b71f230c48 to your computer and use it in GitHub Desktop.
Save nigjo/906578fa4cecd80f9c84e1b71f230c48 to your computer and use it in GitHub Desktop.
a simple JavaScript function to fit some text to a parent via css letter-spacing
/*
* Copyright 2020 Jens Hofschröer.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Original Source: https://gist.github.com/nigjo/906578fa4cecd80f9c84e1b71f230c48
*/
/**
* Adjust letterspacing to a block element.
*/
function adjustSpacing(div, maxWidth=-1, maxSpace=2.5, minSpace=-.2){
let text=div.textContent;
if(text&&text.length>1){
if(maxWidth<=0){
maxWidth = div.parentNode.clientWidth;
}
let space = 0;
while(space<maxSpace && div.clientWidth<maxWidth){
space += 0.1;
div.style.letterSpacing = space+'em';
}
while(space>minSpace && div.clientWidth>maxWidth){
space -= 0.01;
div.style.letterSpacing = space+'em';
}
}
}
<head>
<script src="adjustSpacing.js"></script>
<script>
window.addEventListener('DOMContentLoaded', function(){
let spans=document.querySelectorAll('span');
for(let i=0;i<spans.length;i++){
adjustSpacing(spans[i]);
}
})
</script>
<style>
span{display:inline-block;background-color:yellow;font-size:20pt;}
div{max-width:200px;border:1px solid red;margin:.5em;}
</style>
</head>
<body>
<script>
let text='';
for(let i=1;i<=20;i++){
text+=i%10;
document.body
.appendChild(document.createElement('div'))
.appendChild(document.createElement('span'))
.appendChild(document.createTextNode(text));
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment