Kyuberi
Kyuberi

Reputation: 63

How to align a text to the top of another character?

I would like to align one set of numbers to the top of another set of numbers, just as the smallest currency units that can be found on some price tags.

enter image description here

I've placed two Text inside a Row with CrossAxisAlignment.start but I can't get them both to be the same height.

Row(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: [
    Text(
      '409',
      style: TextStyle(
        fontSize: 20,
        fontWeight: FontWeight.w600,
      ),
    ),
    Text(
      '00',
      style: TextStyle(
        fontSize: 12,
        fontWeight: FontWeight.w600,
      ),
    ),
  ]
)

Upvotes: 1

Views: 690

Answers (2)

Ankit Kumar Maurya
Ankit Kumar Maurya

Reputation: 1207

You need to use RichText for it. You can use WidgetSpan to align the text to the top.

You can take reference from the sample code below:

RichText(
              text: const TextSpan(style: TextStyle(fontSize: 20), children: [
                WidgetSpan(
                    alignment: PlaceholderAlignment.top,
                    child: Text(
                      '\$',
                      style: TextStyle(fontSize: 12),
                    )),
                TextSpan(text: '400'),
                WidgetSpan(
                    alignment: PlaceholderAlignment.top,
                    child: Text(
                      '00',
                      style: TextStyle(fontSize: 12),
                    )),
              ]),
            )

And output is below:

output

Upvotes: 2

Miftakhul Arzak
Miftakhul Arzak

Reputation: 1847

It caused Text widget has padding. The padding is needeed if you type some character like below.

Container(
          color: Colors.green,
          child: Text(
                  'Ğ ğ, H h, X x, I ı, İ i',
                   style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.w600,
                 ),
             ),
     ),

enter image description here

May this is not the best practice to achieve what you want. You can try this code by setting height to 0.8 or other value.

Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          color: Colors.green,
          child: Text(
                '409',
                 style: TextStyle(
                   fontSize: 20,
                   height: 0.8,
                   fontWeight: FontWeight.w600,
                ),
          ),
        ),
        Container(
          color: Colors.yellow,
          child: Text(
                 '00',
                 style: TextStyle(
                   fontSize: 12,
                   height: 0.8,
                   fontWeight: FontWeight.w600,
                 ),
          ),
        ),
      ]
  ),

enter image description here

Upvotes: 1

Related Questions