5

I have a Box in my app with a bunch of children:

Box(modifier = Modifier.fillMaxSize()) {
    Text("a")
    Text("b")
}

I want the text to appear aligned to the top at 20% distance from the start. How do I achieve that?

3 Answers 3

12

To solve this you need two parts:

  1. There're two ways to layout Box content: contentAlignment will apply alignment for all children, and Modifier.align, which can be applied for a specific child.

  2. Usually you can use Modifier.padding in such cases, but not in case when you need relative size. The easiest way to take part of parent size is using Modifier.fillMax..., modifier, in this case Modifier.fillMaxWidth(0.2f) can be applied to a Spacer, placed in a Row with your element.

Box(modifier = Modifier.fillMaxSize()) {
    Row(
        Modifier
            .align(Alignment.TopStart)
    ) {
        Spacer(Modifier.fillMaxWidth(0.2f))
        Text("a")
    }
}
3
  • The BoxWithConstraints did not work for me, this answer works for the first child in the Column or Row. However, for the other children, the fraction is applied to the size that is left to be filled, not the parent size, which is what I need. Commented Oct 20, 2022 at 6:53
  • @PabloValdes I guess you can create a separate row for each item, and they're gonna be displayed on top of each other Commented Oct 21, 2022 at 4:29
  • I tried that and it works great, thanks. I still have to get used to the compose way. Commented Oct 22, 2022 at 2:29
3

follow thewolf's answer

I found this solution.

Let's check this code and the blue box below.

@Composable
fun BoxExample() {
    BoxWithConstraints {
        val boxWithConstraintsScope = this
        val yOffset = 0.2 * boxWithConstraintsScope.maxHeight.value

        Box(
            modifier = Modifier
                .fillMaxSize()
        ) {

            Box(
                modifier = Modifier
                    .height(300.dp)
                    .width(300.dp)
                    .background(Color.Red)

            )
            Box(
                modifier = Modifier
                    .height(200.dp)
                    .width(200.dp)
                    .background(Color.Green)
            )
            Box(
                modifier = Modifier
                    .offset(y =  yOffset.dp)
                    .height(100.dp)
                    .width(100.dp)
                    .background(Color.Blue)
            )
        }
    }
}

Look at Blue box

2

Use the offset/absoluteOffset modifiers along with BoxWithConstraints.

2
  • can you provide an exemple? Commented Feb 23, 2023 at 21:30
  • 1
    Please provide an example so that we can better understand your answer.
    – Ryan Payne
    Commented Mar 28, 2023 at 13:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.