CSS3 Make Text As Big As Possible To FIll Element Without Overflowing
Asked Answered
S

1

10

I'm building a phonegap app for IOS, and I have one <p> tag who's contents must be exactly one line across.

These elements have the full width of the device minus a little outer padding. What I want is for the text to scale to as large a font-size as possible without wrapping to next line, without being cutoff by ellipsis or being clipped, or overflowing.

So far I can accomplish this by precisely setting the font-size (which can be done - there are only about 10 devices to think about), but I'd rather have IOS UIWeview display figure it out for me.

Is it possible to achieve this with CSS?

Souter answered 12/12, 2013 at 21:48 Comment(7)
not possible with vanilla CSS; you'll have to use JavaScript.Oriflamme
If you sure about that, you should post it as an answer, and if no one else offers something better, I'll vote for it, since you caught it first.Souter
fittextjs.com (I'm kind of rushed so don't have time to make a fully fleshed out answer.)Oriflamme
Fittextjs.com isn't centered on my mobile Chrome browser.Pneumoencephalogram
postimg.org/image/462sh7ti5Pneumoencephalogram
It's centered for me on Chrome in iOS. Looks like your browser isn't interpreting the custom font which is why it's not centering. img855.imageshack.us/img855/5306/xl30.jpgOfilia
also fittextjs allows for 'compression' so you can modify to achieve the proper fit. Good little library.Souter
V
3

With CSS only, you can achieve this using Viewport Units by setting the font-size to fill up the space, but now with the text size responsive based on the viewport's width.

p {
    font-size: 7vw; //set to the preferred size based on length of text
}

Here is a simple demo using vw units: https://jsfiddle.net/gmattucc/mh3rsr0o/

You would have to check if vw, vh units are supported in the device you are targeting: http://caniuse.com/#feat=viewport-units

You might also want to check out this article to learn more: https://css-tricks.com/viewport-sized-typography/

Vestige answered 7/4, 2017 at 19:43 Comment(2)
This is definitely the answer nowadays. Unfortunately it wasn't when I posted it. Thanks :)Souter
Didn't see how old his post is haha :)Vestige

© 2022 - 2024 — McMap. All rights reserved.