Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shrink text font size within a div using css

Tags:

html

css

I have a fixed width div of say 120px. The text inside it can change in length with different number of characters. For example, for English language it could be "Compare" and for Russian it could be "Добавить в сравнение".

Now the width of the div is ok for the English wording, but for Russion wording, an overflow occurs. Is there a way in css to shrink the font size in case an overflow occurs.

I know the usage of following css, but I do not want to have ellipsis and want to show the full text even if it gets smaller in size.

overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;

EDIT: The question is marked as duplicate of another question but it is not. The other question says that the div is responsive, not fixed width and also the text inside it can grow, while my question asks about how to shrink the text if it is larger.

like image 477
Imran Ahmed Avatar asked Dec 06 '25 18:12

Imran Ahmed


1 Answers

Here is a function in javascript to shrink the text accordingly.

const correctFontSize = (str, elementWidth, originalSize) => {
  const length = str.length;
  const mult = elementWidth / (originalSize * length);
  let fontSize = originalSize * mult * 2.5;
  if (fontSize > originalSize) fontSize = originalSize;
  return Math.round(fontSize);
};

Here is a code sandbox as well: https://codesandbox.io/s/text-resize-based-on-element-width-fusnit?file=/src/index.js

To get the parent element's width, you can use the parent element's offsetWidth property. See https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth

The wrapper function wraps correctFontSize so it can be used when the window resizes.

like image 86
Yumyummyyy Avatar answered Dec 08 '25 06:12

Yumyummyyy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!