5

I want to scale a letter to the exact height of another element with CSS. For example, I might want to have text that is exactly as high as some image:

enter image description here

How can I achieve this?

When I set font-size equal to the height of the image, the letters are smaller. I can try to adjust this manually, until it looks equal, but I'd like to calculate it.


My current solution is to set line height to the height of the image, and to calculate font-size from the font metrics:

.the_image {
    height: 28px;
    }

.the_M {
    line-height: 28px;
    font-size: calc(28px * 2048 / 1490);
    }

In this case, the font metrics are 2048 UPM (units per em), and the letter "M" is 1490 units high. Dividing the em size (2048 units) by the letter height (1490) results in a factor that scales the "M" to the desired height (here: 28px).

In this case I know the font that I use, because I embed it with @font-face, and I know the metrics of the font because I looked at it in a font editor (I'm using Fontforge and Glyphs to create my fonts), but I'd still like a solution that works for unknown fonts from the user's computer.

Community
  • 1
  • 1
  • I have just inspected part of the text of this question using chrome dev tools and it looks like text "How can I achieve that?" is `17px`, but the computed height for the div is `22px` and I don't think you have much control over it, unless you set the `line-height` to be `17px` as well – Morpheus Apr 07 '15 at 08:21
  • 1
    Why do you need to set the div height? Why can't you just set the font size and leave `div` to expand to the font height? – Morpheus Apr 07 '15 at 08:37
  • @Morpheus I adjusted my example. –  Apr 07 '15 at 08:59
  • http://stackoverflow.com/questions/10718840/make-text-height-100-of-div – Morpheus Apr 07 '15 at 09:52
  • Well, there is [`font-size-adjust`](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size-adjust), which does exactly what you want, but 1) it works on lowercase letters rather than uppercase, and 2) browser support is abysmal. Oh well. Anyway, here is [a fiddle](http://jsfiddle.net/MrLister/yvo5xhkq/). – Mr Lister Apr 07 '15 at 15:31
  • This isn't just a matter of the font being used. It's also a matter of which character glyph is being used. You can't really match that with CSS. – BoltClock Apr 08 '15 at 10:39
  • Have you considered the use of [fontmetrics.js](http://pomax.github.io/fontmetrics.js/) or [font.js](https://github.com/Pomax/Font.js)? – bbh Jun 05 '15 at 09:15

1 Answers1

0

First you need to set position and then inherit height Something like:

    .the_M{
           position : relative;
           height : inherit;
     }
Imran Niloy
  • 31
  • 13