baig772
baig772

Reputation: 3488

How to force a text to fit inside a div

I have a div with width: 200px and I am adding text in it dynamically, I want the text to fit in this div but the text is getting out. I have tried to change the font size on character count but it does not work in all cases, like if string contains character with more width like W or M, the text goes out of the div. Below is my code

if(cs >= 1 && cs <= 4) {
 if(this.engravingFontCaseSenstiveOptions(cText) == "Lower")
    {
        $('#overlay_image_text').css({'margin-top':'-162px'});
        $('#overlay_image_text').css({'font-size':60+'px'});
    }else if(this.engravingFontCaseSenstiveOptions(cText) == "Upper")
    {
        $('#overlay_image_text').css({'margin-top':'-154px'});
        $('#overlay_image_text').css({'font-size':48+'px'});
        $('#overlay_image_text').css({'margin-left':'0px'});
    }else
    {
        $('#overlay_image_text').css({'margin-top':'-162px'});
        $('#overlay_image_text').css({'font-size':60+'px'});
        $('#overlay_image_text').css({'margin-left':'0px'});
    }
 }
 else if(cs == 5) {
   if(this.engravingFontCaseSenstiveOptions(cText) == "Lower")
    {
        $('#overlay_image_text').css({'margin-top':'-152px'});
        $('#overlay_image_text').css({'font-size':54+'px'});
        $('#overlay_image_text').css({'margin-left':'0px'});
    }else if(this.engravingFontCaseSenstiveOptions(cText) == "Upper")
    {
        $('#overlay_image_text').css({'margin-top':'-143px'});
        $('#overlay_image_text').css({'font-size':45+'px'});
        $('#overlay_image_text').css({'margin-left':'0px'});
    }else
    {
        $('#overlay_image_text').css({'margin-top':'-143px'});
        $('#overlay_image_text').css({'font-size':45+'px'});
        $('#overlay_image_text').css({'margin-left':'0px'});
    }
}

Upvotes: 1

Views: 2894

Answers (4)

Asons
Asons

Reputation: 87191

Do like this, where you measure the text size

Made a minor update where the min font size is passed as a param

function getStyle(elem,prop) {
  return window.getComputedStyle(elem,null).getPropertyValue(prop);
}
function setFontSize(elem,minsize) {
  var tst = document.createElement('div');
  tst.textContent = elem.textContent;
  tst.style = 'position:absolute;left:-9999px;display:inline-block;';
  document.body.appendChild(tst);
  tst.style.fontSize = minsize + 'px';
  tst.style.fontWeight = getStyle(elem,'font-weight');
  tst.style.fontFamily = getStyle(elem,'font-family').split(',')[0];
  while (minsize < 1000) {      
    if (parseInt(getStyle(tst,'width')) > 200) {
      elem.style.fontSize = (minsize - 2) + 'px';
      break;
    }
    tst.style.fontSize = minsize++ + 'px';
  }
  document.body.removeChild(tst);
}

setFontSize(document.querySelector('.sizedtext'),5);
.sizedtext {
  width: 200px;
  border: 1px solid;
  font-size: 15px;
  font-weight: normal;
  font-family: Arial;
}
<div class="sizedtext">WWWWWWWWWWWWWWWWWWWWW</div>

Upvotes: 1

Shady Alset
Shady Alset

Reputation: 5714

just I want to suggest an example about fit text inside fixed <div>:

HTML:

<div id="fitText">

</div>

CSS:

#fitText {
height:250px; /* height can be anything */
width:280px; /* width can be anything */
font-size:40px; /* start off big and it will scale down */
background:lightblue;
border:solid 2px blue;
font-family: Arial;
}

JS:

var autoSizeText;

autoSizeText = function() {
var el, elements, _i, _len, _results;
elements = $('#fitText');
if (elements.length < 0) {
    return;
}
_results = [];
for (_i = 0, _len = elements.length; _i < _len; _i++) {
el = elements[_i];
_results.push((function(el) {
  var resizeText, _results1;
  resizeText = function() {
    var elNewFontSize;
    elNewFontSize = (parseInt($(el).css('font-size').slice(0, -2)) - 1) + 'px';
    return $(el).css('font-size', elNewFontSize);
  };
  _results1 = [];
  while (el.scrollHeight > el.offsetHeight) {
    _results1.push(resizeText());
  }
   return _results1;
})(el));
}
return _results;
};

return autoSizeText();

JsFiddle DEMO

I hope it helps, thanks !

Upvotes: 0

kiskeh4ck
kiskeh4ck

Reputation: 26

You can optimize your code even more, you repeat a lot of syntax and do your code slower.

if (cs >= 1 && cs <= 4)
{
    if(this.engravingFontCaseSenstiveOptions(cText) == "Lower")
    {
        $('#overlay_image_text').css({
            'margin-top' : '-162px',
            'font-size' : '60px'
        });
    }
    else if(this.engravingFontCaseSenstiveOptions(cText) == "Upper")
    {
        $('#overlay_image_text').css({
            'margin-top' : '-154px',
            'margin-top' : '-154px',
            'font-size' : '48px',
            'margin-left' : '0px'
        });
    }
    else
    {
        $('#overlay_image_text').css({
            'margin-top' : '-162px',
            'font-size' : '60px',
            'margin-left' : '0px'
        });
    }
}
else if(cs == 5)
{
    if(this.engravingFontCaseSenstiveOptions(cText) == "Lower")
    {
        $('#overlay_image_text').css({
            'margin-top' : '-152px',
            'font-size' : '54px',
            'margin-left' : '0px'
        });
    }
    else if(this.engravingFontCaseSenstiveOptions(cText) == "Upper")
    {
        $('#overlay_image_text').css({
            'margin-top' : '-143px',
            'font-size' : '45px',
            'margin-left' : '0px'
        });
    }
    else
    {
        $('#overlay_image_text').css({
            'margin-top' : '-143px',
            'font-size' : '45px',
            'margin-left' : '0px'
        });
    }
}

Now just so your text does not leave the container div #overlay_image_text added to the word-wrap

#overlay_image_text {
    word-wrap: break-word;
}

You can see more in https://developer.mozilla.org/es/docs/Web/CSS/word-wrap http://www.w3schools.com/cssref/css3_pr_word-wrap.asp

Upvotes: 0

user4227915
user4227915

Reputation:

You can toggle the below class:

.myFitClass {
    overflow: inherit;
    text-overflow: inherit;
    white-space: normal;
    text-align: justify;
}

It would be:

$(element).addClass('myFitClass');
//         ^^^ -> also `removeClass` or even `toggleClass` 

Hope it helps.

Upvotes: 0

Related Questions