-1

I need fit text within the fixed width container, for example i have 150px width in particular div but text is dynamically will come so based one font size change and fit to the container, kindly suggest

Note: only javascript

Samvel Petrosov
  • 7,580
  • 2
  • 22
  • 46
dhana
  • 857
  • 3
  • 11
  • 26
  • 3
    why adding the css tag if you don't want a CSS-based solution ? :) – Valentin Coudert Jun 16 '17 at 13:34
  • 2
    Create a https://jsfiddle.net/ to show us what you've tried. – xiience Jun 16 '17 at 13:34
  • on the `p/span/h` tag add `width: inherit` to css - should work :) (can be done with pure js/jQuery - I know in jQuery is `$('#elem').css('prop', 'value')` - no idea what that is in pure js – treyBake Jun 16 '17 at 13:35
  • @ThisGuyHasTwoThumbs I think OP wants to change the font size so the text fits within the 150px div no matter how long it is – Pete Jun 16 '17 at 13:39
  • @Pete ah I see! Then `overflow: scroll` is needed or something similar – treyBake Jun 16 '17 at 13:40
  • Possible duplicate of [How to: Reduce font-size if a line breaks](https://stackoverflow.com/questions/28485351/how-to-reduce-font-size-if-a-line-breaks) – James Douglas Jun 16 '17 at 13:41

1 Answers1

0

You could use this method, stolen from this answer:

How to: Reduce font-size if a line breaks

Written by AlexK

var divWidth = $("#theDiv").width();
var text = $("#text");
var fontSize = 12;

while (text.width() > divWidth)
  text.css("font-size", fontSize -= 0.5);

text.css("display", "inline");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="theDiv" style="width:200px; border:1px solid red;">
  <span id="text" style="display:none;white-space:nowrap;">This sentence is too large to fit within the div.</span>
</div>

Note that you need JQuery for this.

If you don't want to use jQuery, it shouldn't be hard to replace it with JS.

JSFiddle

James Douglas
  • 3,328
  • 2
  • 22
  • 43