Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to: Reduce font-size if a line breaks

I have a span inside of a div and the div must remain 200px wide and the text must fit on one line within the div. The text within the span is dynamically generated so I can't possibly know which content will break to a new line and which will not.

<div style="width:200px">
  <span style="font-size:12px;">This sentence is too large to fit within the div.</span>
</div>

If I use the CSS property white-space:nowrap; the words will spill to the outside of the div, which of course, we don't want.

How would I reduce the font-size (or zoom) based on if the line breaks or not? I would prefer a CSS answer, but I understand if that is outside of CSS's abilities.

like image 780
ExcellentSP Avatar asked Feb 12 '15 18:02

ExcellentSP


People also ask

How do I reduce text width?

To change your display in Windows, select Start > Settings > Accessibility > Text size. To make only the text on your screen larger, adjust the slider next to Text size. To make everything larger, including images and apps, select Display , and then choose an option from the drop-down menu next to Scale.

How do you line break a text?

<br>: The Line Break element. The <br> HTML element produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant.

How do I change the font size in line app?

Tap settings. Tap chats & Voice Calls. Tap font size. On the pop up, choose a size you wish to use.


Video Answer


1 Answers

One fairly nasty way: loop decreasing the overflowing span until its less that the div width;

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>
like image 150
Alex K. Avatar answered Oct 04 '22 13:10

Alex K.