A Better SuperScript in React Native
const superFontSize = Math.floor(fontSize * 0.6)
const superlineHeight = superFontSize * 1.1const superStyle = {
textAlignVertical: 'top',
fontSize: superFontSize,
lineHeight: superlineHeight
}const regular = {
textAlignVertical: 'bottom',
fontSize: fontSize
}<View style={{flexDirection: 'row', alignItems: 'flex-start'}}> <Text style={superStyle}>Super</Text> <Text style={regular}> Regular Text</Text></View>
WHY
const superFontSize = Math.floor(fontSize * 0.6)
Make the super font about half the size (in this case 60%) of the regular sized text.
const superlineHeight = superFontSize * 1.1
This is important, `lineHeight` for the superscript text must be close to same size as the text. (At first i tried to make this the same height as the regular text and use the textVerticalAlign property but that didn’t give me the results i wanted.)
<View style={{flexDirection: 'row', alignItems: 'flex-start'}}>
At first you might want to Nest your <Text> inside one another but you don't have control of lineHeight on nested <Text> nodes The solution is to put your text in a flex direction row. (note I just have 1 line of text but if you have more you will want to add flexWrap: ‘wrap’ )
The second very important part is the alignItems: ‘flex-start’ . This way all your Characters no matter the size will be aligned on the top!
Presto!
What about other Solutions
Around the web I’ve seen other solutions using extra lineHeight to bring the superscript text up. This has the downsize that if you have several discontinuous blocks of text they will have different heights. This makes aligning them vertically tricky.
I want all this to be vertically centered from the content above and below it but for both sections of regular to be vertically inline with each other. Alternatively I could have wrapped just these parts in another <View>, aligned everything inside it to the bottom and then centered that view, but I like the other solution has it doesnt require me to change the markup and means that all the logic needed for displaying the superscript in an intuitive way is in one place.