Read the original article:Calculate the average spacing between child elements in a parent component
Calculate The Average Spacing Between Child Elements In a Parent Component
Problem Description
The Row component displays multiple child elements (such as multiple Text components) and hopes to achieve the following effects:
- When the sum of the widths of multiple Text components is less than the width of the Row component, the Text components are horizontally centered in the Row component, and the Text components are arranged with equal spacing.
- When the sum of the widths of multiple Text components is greater than the width of the Row component, the Text components that exceed the visible area can be slid and displayed, and the Text components are arranged with equal spacing.
Background Knowledge
- Scroll: It is a scrollable container component. When the layout size of the child component exceeds the size of the parent component, the content can scroll.
- measureText: used to calculate the width of the specified text
Solution
When the total width of child elements (such as a Text component) is greater than the width of the parent component (such as a Row component), nest the Row component within a Scroll component to enable horizontal scrolling and support viewing child elements that exceed the visible area. The spacing between child elements is uniformly set using custom variables, and equal spacing is achieved through margin calculation logic.
When the total width of child elements (such as the Text component) is smaller than the width of the parent component (such as the Row component), use measureText to obtain the width of each child element, calculate the sum of the widths and the remaining space of the parent container, and use the margin calculation logic to achieve equal spacing.
The complete sample code is as follows:
@Entry
@Component
struct Index {
private scrollerForScroll: Scroller = new Scroller()
list: string[] = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6', 'Item 7'] // Simulate total width of child elements exceeding the width of the Row component (parent)
wid: number = 20
parentCompWidth: number = 200 // Width of the parent component
arrayWidthsSum: number = 0 // Total width of child elements
@State arrayWidths: number[] = [] // Collection of child element widths
@State blockNum: number = 0 // Average spacing when total child width is less than parent Row width
// Extract margin calculation logic into a separate method
private getItemMargin(index: number): Margin {
const isFirst = index === 0 // Check if it's the first child element
const isLast = index === this.list.length - 1 // Check if it's the last child element
const defaultMargin = 5 // Default margin when child width exceeds parent width, manually set
if (this.parentCompWidth > this.arrayWidthsSum) { // When total child width is less than parent Row width
// Calculate remaining width of parent and set child element spacing
// First and last child elements get double the average spacing; others get the average spacing
return {
left: isFirst ? this.blockNum : this.blockNum / 2,
right: isLast ? this.blockNum : this.blockNum / 2
}
} else {
// First and last child elements get double the default margin; others get the default margin
return {
left: isFirst ? defaultMargin : defaultMargin / 2,
right: isLast ? defaultMargin : defaultMargin / 2
}
}
}
aboutToAppear(): void {
// Get the width of each item in the list
this.arrayWidths = this.list.map(text =>
this.getUIContext().px2vp(this.getUIContext().getMeasureUtils().measureText({
textContent: text,
fontSize: 15
}))
)
// Calculate total width of all items
this.arrayWidthsSum = this.arrayWidths.reduce((acc, curr) => acc + curr, 0)
// If total child width is less than parent Row width, calculate remaining width and divide it into (number of items + 1) parts as average spacing
this.blockNum = (this.parentCompWidth - this.arrayWidthsSum) / (this.list.length + 1)
}
build() {
Column() {
Scroll(this.scrollerForScroll) {
Row() {
ForEach(this.list, (item: string, index: number) => {
Text(item)
.fontSize(15)
.height(100)
.backgroundColor(Color.Pink)
.margin(this.getItemMargin(index)) // Dynamically set child element spacing
})
}
}
.scrollBar(BarState.Off) // Hide scroll bar
.scrollable(ScrollDirection.Horizontal) // Enable horizontal scrolling
.width(this.parentCompWidth) // Set parent component width
.height(200)
.border({ width: 1, color: Color.Black })
}
.width('100%')
.height('100%')
}
}
When the sum of the widths of child elements (such as the Text component) is greater than the width of the parent component (such as the Row component), the effect diagram is as follows:
Restrictions and Limitations
This example supports API Version 19 Release and above.
This example supports HarmonyOS SDK Version 5.1.1 Release and above.
This example requires DevEco Studio Version 5.1.1 Release and above to compile and run

Top comments (0)