Reputation: 29655
I have an HTML text field that is 3 characters. If the user types 4 characters, I want the font size to shrink so that the four characters will fit.
Acrobat has this behavior for forms. I want this behavior in HTML.
That is, if I have a text field with 3 characters:
And the user types a 4, I want the text to shrink:
Upvotes: 1
Views: 2158
Reputation: 314
You need to use javascript.
This works by checking if the input can scroll, and if it can, it means that the content has overflowed, in which case the font size should get smaller.
Hope this helps!
function changefontsize() {
var myInput = document.getElementById('myInput');
if(isOverflown(myInput)) {
while (isOverflown(myInput)){
currentfontsize--;
myInput.style.fontSize = currentfontsize + 'px';
}
}else {
currentfontsize = 13;
myInput.style.fontSize = currentfontsize + 'px';
while (isOverflown(myInput)){
currentfontsize--;
myInput.style.fontSize = currentfontsize + 'px';
}
}
}
function isOverflown(element) {
return element.scrollWidth > element.clientWidth;
}
#myInput {
padding:5px;
border-radius:3px;
font-family:Arial;
width:100px;
font-size:13px;
height:20px;
}
Type Here -> <input type="text" id="myInput" onkeypress="changefontsize()" onchange="changefontsize()">
Upvotes: 5
Reputation: 857
This is not possible with HTML/CSS - this solution uses JS+JQuery
Found this: https://github.com/vxsx/jquery.inputfit.js Demo: http://vxsx.github.io/jquery.inputfit.js/
<input type="text" name="younameit" id="input">
<script type="text/javascript">
$('#input').inputfit();
</script>
Upvotes: 1
Reputation: 683
I think what you want can be done with some very simple javascript methods. But, unfortunately there is no method of doing this in html or css. This next code is something I found, made by u/adactio. On github.
<script>
window.fitText( document.getElementById("responsive_headline") );
</script>
window.fitText( document.getElementById("responsive_headline"), 1.2 );
// turn the compressor up (font will shrink a bit more aggressively)
window.fitText( document.getElementById("responsive_headline"), 0.8 );
// turn the compressor down (font will shrink less aggressively)
Make sure to edit the 'responsive_headline' out! Cheers!
Upvotes: 1