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?

2
  • 2
    It's not possible Commented Sep 26, 2016 at 19:47
  • 3
    This is not a duplicate question. Text length !== container width. Commented Mar 23, 2018 at 16:52

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.