Search code examples
nativescript

Nativescript: how to vertically align text inside Label on Android


The text inside label is vertically aligned by default on iOS, however on Android it's not. How to center it vertically on Android (I'm interested in centering text inside Label, not wrapping label inside any other layout to get the same effect)?

To see what I mean run the next code on iOS and Android.

xml:

<Page xmlns="http://schemas.nativescript.org/tns.xsd" loaded="onLoaded">
    <Label text="test" />
</Page>

css:

Label {
    width: 60;
    height: 60;
    text-align: center;
    background-color: aquamarine;
    border-radius: 30;
}

Solution

  • Set the padding accordingly to the (width - font-size) / 2 (rough approximation may differ for smaller boxes where Capital or small letters has different center point)

    e.g.

    Label {
        width: 60;
        height: 60;
        border-radius: 30;
        text-align:center;
        background-color: aquamarine;
        padding: 15;
        font-size: 20;
    }
    

    or example with bigger sizes:

    Label {
        width: 200;
        height: 200;
        border-radius: 100;
        text-align:center;
        background-color: aquamarine;
        padding: 80;
        font-size: 20;
    }
    

    p.s If you wrap your label in StackLayout you won't need height

    e.g.

      <StackLayout>
        <Label text="test" class="title"/>
      </StackLayout>
    
    Label {
        width: 200;
        border-radius: 100;
        text-align:center;
        background-color: aquamarine;
        padding: 80;
        font-size: 20;
    }