2

I have responsive boxes (divs) containing dynamic texts. The texts are normally short enough to fit in the boxes but sometimes some of them are larger and don't fit.

I'm trying to resolve this issue truncating the texts with text-overflow: ellipsis but this is not ideal because info is lost. Media queries break points don't help either because they affect the whole page and not only the boxes with long texts.

How would you make a non-fitting text responsive so its size is reduced automatically to fit in its holder box?

IsidroGH
  • 2,037
  • 19
  • 27
  • 1
    This isn't possible with CSS only. You can use some JavaScript that checks the width of the content and reduces the font size until it fits, but that's not ideal; firstly, it can't reduce the font size below the minimum size as set in the user's prefs, and secondly, if there is no minimum set, the routine might be tempted to reduce it all the way down to an unreadable 1px if the text is very large. – Mr Lister Mar 17 '17 at 11:48
  • So you should look for a workaround. How about a horizontal scrollbar? A vertical scrollbar? – Mr Lister Mar 17 '17 at 11:49
  • Just wanted to be sure it can't be done with CSS only. I'll try the JavaScript approach although it seems a bit dirty. (I can't use scrollbars) – IsidroGH Mar 17 '17 at 12:00
  • Take a look at this answer from another similar question: https://stackoverflow.com/a/6112914/1129920 With a bit of JS you are able to make the text resize to the size of the div. – krisboud Mar 17 '17 at 11:50
  • Would have been better as a comment. Only post answers when they can directly help the author of the question. If you're going to recommend things with no code do it within the comments. – Ousmane D. Mar 17 '17 at 11:51
  • I'll try this although I was trying to avoid JS hacks. – IsidroGH Mar 17 '17 at 12:05

3 Answers3

1

I was looking to achieve it too, but i only found a good working Js to do so. Can you take a look on it fittext.js

Evrard-c
  • 391
  • 3
  • 14
0

If you have not set the height of the divs, then the text inside them will only increase the size of the divs but will not go out of them.

if you are trying to truncate why not use overflow: hidden.

Alternatively, you can create a class targeting the divs who you suspect might contain long text and make them have em value as size. Instead of px

Dhananjay Gupta
  • 316
  • 2
  • 11
  • I'm trying to avoid truncating the texts. Texts are dynamic so I don't know which and when a `div` will be containing a long text. – IsidroGH Mar 17 '17 at 12:03
-1

One Possible solution is to keep width and height of parent element in percentages and then make child element as inline blocks. This is not the perfect solution at very low resolutions, but will work in your case.

.parent{
    width: 20%; 
    height: 20%;
}

.child{
   display: inline-block;
}
san A
  • 177
  • 2
  • 13