Skip to content
Home » Jetpack Compose text vertical align

Jetpack Compose text vertical align

  • by
Jetpack Compose text vertical align

1. Overview

In this article, we will learn to vertical align the text in Jetpack compose. To learn more about other Jetpack components, refer to our articles.

2. Jetpack Compose Text

A Text is always the core for any UI. In Jetpack compose, you don’t need to overwrite properties and methods or extend big classes to have a specific design. Jetpack handles most of the complexities for you.

The Jetpack compose provides the following composable for displaying Text:

  1. BasicText (shortened form with basic functionalities)
  2. BasicTextField (shortened form with basic functionalities)
  3. Text (follows Material design guidelines)
  4. TextField (follows Material design guidelines)

For example, you can display the test using the Text composable as below:

@Composable
fun HelloWorldText() {
  Text("Hello World")
}

3. Text horizontal alignment

The textAlign parameter allows setting the alignment of the text within a Text composable surface area horizontally. TextAlign controls how the text aligns in the space it appears. To know more about horizontal alignment, refer to this article.

3.1. Vertical align text

However, you must wrap the Text composable in another container for vertical alignment.

Text center vertically in Box - Jetpack Compose
Text center vertically in Box – Jetpack Compose

You can use Box to put elements on top of another. Box also supports configuring specific alignment of the elements it contains.

For example, the following code wraps the "Hello World" text within the Box container. By defining the contentAlignment as center for the Box, the text will appear center vertically on the screen.

@Preview(showBackground = true)
@Composable
fun alignTextCenterBox() {
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = "Hello World",
        )
    }
}

Similarly, you can wrap the Text composable inside the Column container. A Column is a layout composable that places its children in vertical sequence.

The composable Column supports the following positioning behaviors:

  1. Vertical Arrangement (Used to specify the vertical arrangement of the layout’s children in Column layouts)
  2. Horizontal Alignment (Used to define the horizontal alignment of a Column layout inside a parent layout.)

To understand the verticalArrangement and horizontalAlignment of Column composable, refer to this article.

@Preview(showBackground = true)
@Composable
fun alignTextCenterColumn() {
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = "Text",
        )
    }
}

4. Conclusion

To sum up, we have learned the vertical align the Text composable in Jetpack Compose.