width
Common
Modifier in Compose Foundation Layout
Declare the preferred width of the content to be the same as the min or max intrinsic width of the content. The incoming measurement [Constraints] may override this value, forcing the content to be either smaller or larger.
See [height] for options of sizing to intrinsic height. Also see [width] and [widthIn] for other options to set the preferred width.
Last updated:
Installation
dependencies {
implementation("androidx.compose.foundation:foundation-layout:1.8.0-alpha04")
}
Overloads
@Stable
fun Modifier.width(intrinsicSize: IntrinsicSize)
@Stable
fun Modifier.width(width: Dp)
Code Examples
SameWidthBoxes
@Composable
fun SameWidthBoxes() {
// Builds a layout containing three Box having the same width as the widest one.
//
// Here width min intrinsic is adding a width premeasurement pass for the
// Column, whose minimum intrinsic width will correspond to the preferred width of the largest
// Box. Then width min intrinsic will measure the Column with tight width, the
// same as the premeasured minimum intrinsic width, which due to fillMaxWidth will force
// the Box's to use the same width.
Box {
Column(Modifier.width(IntrinsicSize.Min).fillMaxHeight()) {
Box(modifier = Modifier.fillMaxWidth().size(20.dp, 10.dp).background(Color.Gray))
Box(modifier = Modifier.fillMaxWidth().size(30.dp, 10.dp).background(Color.Blue))
Box(modifier = Modifier.fillMaxWidth().size(10.dp, 10.dp).background(Color.Magenta))
}
}
}
SameWidthTextBoxes
@Composable
fun SameWidthTextBoxes() {
// Builds a layout containing three Text boxes having the same width as the widest one.
//
// Here width max intrinsic is adding a width premeasurement pass for the Column,
// whose maximum intrinsic width will correspond to the preferred width of the largest
// Box. Then width max intrinsic will measure the Column with tight width, the
// same as the premeasured maximum intrinsic width, which due to fillMaxWidth modifiers will
// force the Boxs to use the same width.
Box {
Column(Modifier.width(IntrinsicSize.Max).fillMaxHeight()) {
Box(Modifier.fillMaxWidth().background(Color.Gray)) { Text("Short text") }
Box(Modifier.fillMaxWidth().background(Color.Blue)) {
Text("Extremely long text giving the width of its siblings")
}
Box(Modifier.fillMaxWidth().background(Color.Magenta)) { Text("Medium length text") }
}
}
}
SimpleWidthModifier
@Composable
fun SimpleWidthModifier() {
Box { Box(Modifier.width(100.dp).aspectRatio(1f).background(Color.Magenta)) }
}