0

I have a page for which it is essential that certain elements do not exceed certain widths.

For this case, I know that I can achieve this with any monospaced font such that the horizontal "stride" from one character to the next does not exceed a certain threshold.

I've found that this is nowhere near enough to enforce this constraint:

.someclass {
  font-family: monospace;
  font-width: 13px;
}

or even something more specific, like

.someclass {
  font-family: consolas, monaco, courier, monospace;
  font-width: 13px;
}

...because the fonts that fit this specification can vary wildly in their widths. (In fact, I realized this when I discovered that the above CSS produces satisfactory results in Chrome, but totally unacceptable ones in Firefox, because the font the latter uses to satisfy the directive above is vastly wider than the one that Chrome uses.)

IOW, essentially, what I'd like to do is something like:

.someclass {
  font-family: monospace;
  font-width: 8px;
}

AFAIK, this is not possible.

Is there some other way to impose a hard bound on font widths with CSS?

0

3 Answers 3

3

I think you need font-stretch:

.someclass {
  font-family: monospace;
  font-stretch: ultra-expanded;
}

font-stretch accepts one of the following values:

ultra-condensed
extra-condensed
condensed
semi-condensed
normal
semi-expanded
expanded
extra-expanded
ultra-expanded
inherit

Look it at mdn

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

1 Comment

How does this solve the problem? How does he know which font-stretch value to use?
1

You are going to need to iterate over font sizes until you find one that satisfies your constraints. Here is some rough pseudo-code for the one-line case:

function adjust_font_size(elt, start_size) {
    while (elt.scrollWidth > elt.offsetWidth) {     // doesn't fit
        elt.style.fontSize = --start_size + "px";   // reduce font size
    }
}

Comments

0

As far as I know there is no way to force that constraint. The exact width depends greatly on what your user-agent is and what device you are using.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.