2

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.

Kreutzer
  • 328
  • 4
  • 12
  • I don't think this is possible with CSS only. I would be happy to be proven wrong, but you will probably need some JavaScript. – Andrew Jun 27 '13 at 11:31
  • I've got it to work with js, but a CSS only way is what I truely fancy – Kreutzer Jun 27 '13 at 11:37
  • you can keep the font-size whatever you want and give the parent element (div) `display: inline-block`. – Mr_Green Jun 27 '13 at 11:39
  • possible duplicate of [Auto-size dynamic text to fill fixed size container](http://stackoverflow.com/questions/687998/auto-size-dynamic-text-to-fill-fixed-size-container) – yoeriboven Jun 27 '13 at 11:42

2 Answers2

1

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

Community
  • 1
  • 1
yoeriboven
  • 3,541
  • 3
  • 25
  • 40
1

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" );
    }
});
Community
  • 1
  • 1
Praveen Gowda I V
  • 9,569
  • 4
  • 41
  • 49