0

Consider the following markup and styles:

<div>
    Some text Some text Some text 
</div>

div{
    width: 100px;
}

How can I do that the text-content of div have a font-size's property value such that there is maximum font-size value in which text-content of div lie on one line entirely? jsFiddle

  • may be duplicate of http://stackoverflow.com/questions/3401136/resize-font-to-fit-in-a-div-on-one-line – immayankmodi Feb 12 '14 at 04:25
  • There is no *simple* pure-CSS solution. You will either have to resort to Javascript and live knowing that clients with Js disabled won't see what you expect them to or create a series of media queries. – Etheryte Feb 12 '14 at 08:33

3 Answers3

1

Try this:

HTML:

<div id="container">
    <span id="text_container">whatever text you want</span>
</div>

CSS:

#container {
    background:cyan;
    width:200px;
}
#text_container {
    white-space:nowrap;
}

JS:

var container = $("#container"),
text_container = $("#text_container"),
start_size = 100,
container_width = container.width();

text_container.css('font-size', start_size + 'px');


while (text_container.width() > container_width) {
    text_container.css('font-size', start_size--+'px');
}

DEMO

display-name-is-missing
  • 4,424
  • 5
  • 28
  • 41
0

Do this instead:

div{
    min-width: 200px;
}

By setting a minimum width you ensure that the div never gets small enough to collapse the text to multiple lines.

Demo: http://jsfiddle.net/96daR/4/

agconti
  • 17,780
  • 15
  • 80
  • 114
0

Give a id to the div, say id="myDiv"

Get height using one of this

javascript:

var myDiv = document.getElementById("myDiv");
h=myDiv.clientHeight;
h=myDiv.scrollHeight;
h=myDiv.offsetHeight;

or in jquery:

h=$("#myDiv").height();
h=$("#myDiv").innerHeight();
h=$("#myDiv").outerHeight();

Next set the font-size using this:

document.getElementById("myDiv").style.font-size=h+"px";
AtanuCSE
  • 8,832
  • 14
  • 74
  • 112