Reputation: 338
I'm letting a user input a string and then I enter that string into some <div>
.
The <div>
has a - fixed length - and I want the text to always fit inside it.
Is there a way to set the font-size
attribute to be relative to the input length (as opposed to the container width, which is not the case)? Hopefully with CSS only.
Thanks.
Upvotes: 2
Views: 2486
Reputation: 3571
I don't think you can do that with only CSS. What you can do is get the length of the text, do some calculations and set the size of the text.
Update
I found this: Auto-size dynamic text to fill fixed size container
Upvotes: 1
Reputation: 9637
You can achieve this using jQuery, I don't think CSS only is possible, checkout this fiddle
Note: This was already answered by DanielB for this question
HTML
<div id="fitin">
<div>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div>
</div>
CSS
#fitin {
width: 300px;
height: 100px;
border: 1px solid black;
overflow: hidden;
font-size: 1em;
}
Javascript
$(function() {
while( $('#fitin div').height() > $('#fitin').height() ) {
$('#fitin div').css('font-size', (parseInt($('#fitin div').css('font-size')) - 1) + "px" );
}
});
Upvotes: 1