Domanda

I'm trying to force text to fill a div, while div height and width and unknown. The text size should be flexible, depending on parent. I want to archieve something like this:

enter image description here

The page is mobile only, so I need to support all android/iphone browsers. The main problem is that each mobile browser support different things and it's hard to get such thing working on most* devices.

I tried setting meta viewport width="640" - it's working well on the newest major browser but all lower browser have their own realisation and it's breaking.

The next thing which came to my mind is using viewport units, but their support is bad too (http://caniuse.com/viewport-units)

I came up with the following code for the font-size:

var ratio = parent.offsetWidth * 85/100 / text.offsetWidth - 0.3;

text.style.fontSize = (10 * ratio > 85 ? 85 : 10 * ratio) + "px";

but still it's not that precise and vectical centering is still a mistery.

È stato utile?

Soluzione

Maybe setting font-size dynamically is the right way to achieve this. But rather than width, you can consider using height as ratio. So calculating div's height is probably ineluctable.

For vertical alignment, there are several solutions:

  1. Wrap text in a span. And set the span's display to inline-block. Add to the span a pseudo element of which the height is 100%. Set vertical-align: middleto both span and pseudo element, as described here. Make sure that you set the parent div's height, using Javascript if necessary.

  2. Set the line-height to the same as the div's height.

  3. Set both parent div and children span's height, and display: block; margin: auto

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top