1

Is it possible to make the font-size parameter depend on the length of the text? Of course I could realize this is possible with JavaScript, but I don't want to. ;)

I have a box which has 140px width and height. The content should be 100px w+h (padding of the box: 20px). My text should use this 100px width best. Also on a text change on the page (AJAX) the text should assign to width=100px.

Is that possible?

David L
  • 32,885
  • 8
  • 62
  • 93

1 Answers1

2

If you know the length of the text in advance then you can set up media queries based on the screen size in your CSS to tailor the font-size accordingly.

@media (max-width: 367px) {
  .myContainer {
    font-size: 8px;
  }
}
@media (min-width: 368px) and (max-width: 1024px) {
  .myContainer {
    font-size: 12px;
  }
}
@media (min-width: 1025px) {
  .myContainer {
    font-size: 16px;
  }
}

If you are dynamically generating the text with a server-side technology you should be able to see your text length and set an appropriate class to size the font:

// Example pseudo-code to illustrate the point...
int len = myText.length();
if (len > 2000) {
  setOutputClass("smallestSize");
} else if (len > 1000 && len < 2000) {
  setOutputClass("mediumSize");
} else {
  setOutputClass("largestSize");
}

And with that corresponding class rules in your CSS:

.smallestSize {
  font-size: 8px;
}

.mediumSize {
  font-size: 12px;
}

.largestSize {
  font-size: 16px;
}

I'm pretty sure there is no way to determine the length of text within CSS, so ultimately you may be forced to use JavaScript or approach the solution a bit differently.

Dave Cripps
  • 929
  • 7
  • 11