DEV Community

刘年华
刘年华

Posted on

Spacing Solution for Span Components in HarmonyOS Text

Spacing Solution for Span Components in HarmonyOS Text

I. Problem Analysis

In HarmonyOS development, Span child components within Text components cannot directly set margin/padding properties. Instead, text-level attributes must be used to control spacing. After thorough testing, using letterSpacing combined with special placeholders has proven to be the optimal solution.

II. Technical Solution

1. Core API

letterSpacing

  • Purpose: Sets the character spacing within the same Span
  • Unit: vp (virtual pixels)
  • Characteristics: Supports both positive and negative values (positive values increase spacing, negative values decrease spacing)

Image description

Demo Implementation

@Entry
@Component
struct Index {
  build() {
    Column() {
      Text() {
        Span('Sample Text')
          .fontSize('20fp')
          .textBackgroundStyle({color: Color.Green, radius: "5vp"})
          .fontColor(Color.White)
        // Spacing control using letterSpacing
        Span(' ').letterSpacing(10)
        Span('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua')
          .fontSize('20fp')
      }.maxLines(2).textOverflow({ overflow: TextOverflow.Ellipsis }).width('80%')
    }.width('100%').alignItems(HorizontalAlign.Center)
  }
}
Enter fullscreen mode Exit fullscreen mode

2. Implementation Principle

The spacing between Spans is controlled by inserting a space character Span or using \u200B (zero-width space) instead of a regular space, and then applying letterSpacing to it:

As you can see in the key code above, I've added an empty Span with letterSpacing where spacing is needed. This effectively creates the desired spacing between Spans.

3. Key Benefits

  • Simple implementation: Requires minimal code changes
  • Precise control: Allows fine-tuning of spacing with exact pixel values
  • Cross-device consistency: Works reliably across different screen sizes and densities
  • Performance efficient: Minimal impact on rendering performance

4. Usage Recommendations

  • For small spacing adjustments (1-5vp), use regular space characters
  • For larger gaps (>5vp), the letterSpacing approach is more reliable
  • When working with mixed text styles, place the spacing Span between different styled content
  • Test on multiple device sizes to ensure consistent appearance

III. Conclusion

This solution provides a reliable workaround for the limitation of Span components in HarmonyOS Text. By leveraging the letterSpacing property with empty space characters, developers can achieve precise control over spacing between text segments without compromising performance or compatibility.

Top comments (0)