【HarmonyOS7】ArkTS通用属性实战(一):一文吃透尺寸设置 width/height/size

前言
在 ArkTS 声明式开发范式里,**通用属性(Universal Attributes)**是所有组件共有的属性方法:无论是 Text、Column 还是 Image,只要挂上 .width()、.padding(),行为规则完全一致。把通用属性吃透,等于掌握了一套"到处可用"的布局词汇表。
本系列是 HarmonyOS7 通用属性实战的第一篇,对应官方文档《尺寸设置》一节,我们把最常用的尺寸类属性一次讲完:
width/height/size:设置组件自身的宽高padding/margin:内边距与外边距layoutWeight:父容器主轴上的权重分配constraintSize:最小 / 最大尺寸约束
这一篇主要回答三个问题:固定值、百分比、calc 表达式各在什么时候用;layoutWeight 和 constraintSize 谁说了算;"子组件溢出""百分比参考错了对象"这类问题怎么排查。
环境说明:本系列示例在 DevEco Studio 中开发,基于 Stage 模型。
width/height/size等基础接口从 API 7 起可用,calc计算特性从 API 10 起可用,示例代码整体兼容 API 12 及以上版本,可直接运行。
一、知识总览

1.1 Length:尺寸参数的统一类型
width、height、padding、margin 等接口的参数类型都是 Length,它有四种写法:
| 写法 | 示例 | 说明 |
|---|---|---|
| number | .width(120) |
数字默认单位为 vp(虚拟像素,随屏幕密度缩放) |
| string(百分比) | .width('50%') |
相对父容器内容区的宽度;百分比计算参考最近设置了固定大小的祖先节点 |
| string(calc) | .width('calc(100% - 32vp)') |
API 10 起支持,运算符与数值之间必须用空格隔开 |
| Resource | .width($r('app.float.card_width')) |
引用资源文件中定义的尺寸 |
1.2 本篇属性速查表
| 属性 | 作用 | 关键规则 |
|---|---|---|
width(value: Length) |
设置组件宽度 | 缺省时使用内容需要的宽度;子组件超出父组件会溢出显示 |
height(value: Length) |
设置组件高度 | 同上 |
size(value: SizeOptions) |
一次设置宽高 | 参数为 { width, height },等价于分别调用 |
padding(value) |
内边距 | 内容与边框之间的留白;百分比以父容器宽度为基础值 |
margin(value) |
外边距 | 参与定位计算,视为组件大小的一部分 |
layoutWeight(value: number) |
主轴权重分配 | 仅 Row/Column/Flex 内生效;生效时忽略子组件自身 width/height,但保留 min 约束 |
constraintSize(value) |
最小/最大约束 | minWidth/maxWidth/minHeight/maxHeight,优先级高于 width/height |
二、环境准备
- 打开 DevEco Studio,选择
Create Project; - 模板选择
Empty Ability(Phone 平台),点击 Next; - 填写工程名(如
SizeDemo),编译 SDK 选择 API 12 及以上,Finish; - 工程创建完成后,展开
entry/src/main/ets/pages/,打开Index.ets,本篇的代码都写在这个文件里。
后面几步都是把写好的代码粘贴进 Index.ets 后运行预览(工具栏 Previewer 或真机运行),没有任何额外配置。
三、案例实战:把七个属性写进一个页面
下面这个页面把 7 个属性都装了进去:固定值、百分比、calc 三种宽度写法各占一段,layoutWeight 权重分配和 constraintSize 最值约束各一组,最后是一个用滑块动态驱动尺寸的小交互。
将 Index.ets 的全部内容替换为以下代码:
typescript
// 尺寸设置案例:width / height / size / padding / margin / layoutWeight / constraintSize
@Entry
@Component
struct SizeDemo {
@State avatarSize: number = 64;
build() {
Scroll() {
Column({ space: 18 }) {
Text('一、固定值 / 百分比 / calc 表达式')
.fontSize(16)
.fontWeight(FontWeight.Bold)
.width('100%')
Column({ space: 6 }) {
Text('固定值:width(120)')
.fontSize(12)
.fontColor('#616161')
.width('100%')
Column()
.width(120)
.height(36)
.backgroundColor('#90CAF9')
.borderRadius(6)
}
.width('100%')
Column({ space: 6 }) {
Text("百分比:width('50%')")
.fontSize(12)
.fontColor('#616161')
.width('100%')
Column()
.width('50%')
.height(36)
.backgroundColor('#A5D6A7')
.borderRadius(6)
}
.width('100%')
Column({ space: 6 }) {
Text("动态计算:width('calc(100% - 32vp)')")
.fontSize(12)
.fontColor('#616161')
.width('100%')
Column()
.width('calc(100% - 32vp)')
.height(36)
.backgroundColor('#FFCC80')
.borderRadius(6)
}
.width('100%')
Text('二、size 统一设置与 layoutWeight 权重分配')
.fontSize(16)
.fontWeight(FontWeight.Bold)
.width('100%')
Row({ space: 8 }) {
Column()
.size({ width: 56, height: 56 })
.backgroundColor('#4DB6AC')
.borderRadius(10)
Column()
.size({ width: 56, height: 56 })
.backgroundColor('#4DB6AC')
.borderRadius(10)
}
.width('100%')
Row({ space: 8 }) {
Text('热点')
.layoutWeight(1)
.height(36)
.textAlign(TextAlign.Center)
.backgroundColor('#FFCC80')
.borderRadius(6)
Text('推荐(权重为其他两项的两倍)')
.layoutWeight(2)
.height(36)
.textAlign(TextAlign.Center)
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.backgroundColor('#FFB74D')
.borderRadius(6)
Text('我的')
.layoutWeight(1)
.height(36)
.textAlign(TextAlign.Center)
.backgroundColor('#FFCC80')
.borderRadius(6)
}
.width('100%')
Text('三、padding 内边距与 margin 外边距')
.fontSize(16)
.fontWeight(FontWeight.Bold)
.width('100%')
Column() {
Column() {
Text('内容区域')
.width('100%')
.height(44)
.textAlign(TextAlign.Center)
.fontSize(14)
.backgroundColor('#90CAF9')
.borderRadius(6)
}
.padding(16)
.backgroundColor('#FFFFFF')
.borderRadius(12)
.margin(12)
}
.width('100%')
.backgroundColor('#EEEEEE')
.borderRadius(12)
Text('四、constraintSize 最小 / 最大约束')
.fontSize(16)
.fontWeight(FontWeight.Bold)
.width('100%')
Row({ space: 12 }) {
Text('短标签')
.constraintSize({ minWidth: 96 })
.height(36)
.textAlign(TextAlign.Center)
.fontSize(13)
.backgroundColor('#B39DDB')
.borderRadius(6)
Text('这是一段很长很长很长很长的说明文字')
.constraintSize({ maxWidth: 150 })
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.height(36)
.textAlign(TextAlign.Center)
.fontSize(13)
.backgroundColor('#FFAB91')
.borderRadius(6)
}
.width('100%')
Text('五、动态尺寸:状态变量驱动宽高')
.fontSize(16)
.fontWeight(FontWeight.Bold)
.width('100%')
Column() {
Column()
.width(this.avatarSize)
.height(this.avatarSize)
.borderRadius(this.avatarSize / 2)
.backgroundColor('#4DD0E1')
Text('当前头像尺寸:' + this.avatarSize + ' vp')
.fontSize(13)
.fontColor('#616161')
.margin({ top: 8 })
}
.width('100%')
Slider({
value: this.avatarSize,
min: 40,
max: 120,
step: 1
})
.width('100%')
.onChange((value: number, mode: SliderChangeMode) => {
this.avatarSize = value;
})
}
.width('100%')
.padding(20)
}
.width('100%')
.height('100%')
.backgroundColor('#F5F5F5')
}
}
运行后你会看到一个从上到下依次排布五个板块的演示页,拖动底部滑块可以实时改变头像尺寸。
四、核心代码逐行解读
4.1 固定值与百分比:width(120) 与 width('50%')
typescript
Column()
.width(120) // 数字 120,单位 vp,不随屏幕密度变化
.height(36)
数字入参单位是 vp(virtual pixel)。设计稿上标注 120,直接写 120 即可,框架会按屏幕密度换算成物理像素,保证在不同分辨率的设备上视觉宽度一致。
typescript
Column()
.width('50%') // 字符串百分比,相对父容器内容区
百分比是相对父容器内容区 (父容器尺寸减去 border、padding 之后剩余的区域)计算的。如果祖先链上有嵌套容器,记住一条规则:百分比参考的是最近设置了固定大小的祖先节点。这也是很多"百分比没生效"问题的根源------父容器自己都没有确定尺寸。
4.2 calc 表达式:混合单位的动态计算
typescript
Column()
.width('calc(100% - 32vp)') // 宽度 = 父容器宽度 - 32vp
calc 从 API 10 开始支持,允许把百分比和 vp/fp 等单位放进一个表达式里做加减乘除运算,最典型的场景就是"占满父容器,但左右各留 16vp":calc(100% - 32vp)。
书写时有三个细节:
- 运算符两侧必须有空格 :
calc(100%-32vp)是无效写法; - 括号可以嵌套,支持
+ - * /; - 百分比部分依然遵循"参考最近固定大小祖先"的规则。
4.3 size() 与 layoutWeight
typescript
Column()
.size({ width: 56, height: 56 }) // 一次设置宽高
size() 接收一个 SizeOptions 对象,把 width 和 height 一口气写完,适合宽高成对出现的场景(正方形头像、图标占位块)。它和分别调用 .width(56).height(56) 效果完全相同,纯属书写习惯取舍。
typescript
Row({ space: 8 }) {
Text('热点').layoutWeight(1) // 分到 1 份
Text('推荐').layoutWeight(2) // 分到 2 份
Text('我的').layoutWeight(1) // 分到 1 份
}
layoutWeight 是 Row/Column/Flex 主轴上的"分蛋糕"机制,规则有三条:
- 未设置
layoutWeight(或值为 0)的子组件优先占位,它们占完后主轴剩下的空间才叫"剩余空间"; - 设置了权重的子组件按权重比例瓜分剩余空间,分配时会忽略它们自身的 width/height ,但
constraintSize的 min/max 约束仍然保留; - 权重值为
[0, +∞),负数按 0 处理。
上例中三个 Tab 没有设置宽度,整行空间按 1:2:1 分配,中间"推荐"始终是两侧的两倍宽。相比写死百分比,权重方式在内容长度变化时依然保持比例,是最常用的等分手段。
4.4 padding 与 margin:一对最容易混淆的留白
typescript
Column() {
Text('内容区域') // content
.backgroundColor('#90CAF9')
}
.padding(16) // padding:内容与组件边缘之间的留白
.backgroundColor('#FFFFFF')
.margin(12) // margin:组件与邻居之间的留白
区分它们只需要一句话:padding 撑大自己的内容区域,margin 是把自己往外推。注意两个隐藏规则:
- 两者设置百分比时,上下左右都以父容器的 width 为基础值(不是各自方向);
margin参与定位计算------在 Row、Column、Flex 交叉轴上布局时,子组件连同 margin 一起参与对齐计算。
4.5 constraintSize:给尺寸上一道"保险"
typescript
Text('短标签')
.constraintSize({ minWidth: 96 }) // 内容再短也不小于 96vp
Text('这是一段很长很长很长很长的说明文字')
.constraintSize({ maxWidth: 150 }) // 内容再长也不超过 150vp
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
constraintSize 接收 ConstraintSizeOptions,四个字段分别是 minWidth/maxWidth/minHeight/maxHeight,默认值为 minWidth: 0, maxWidth: Infinity(高度同理)。它解决的是"内容不确定"场景:标签可能很短也可能很长,用最小值兜住下限、最大值封住上限,再配合单行省略号,就不会被内容撑破布局。
最关键的一条规则 :constraintSize 的优先级高于 width/height。当两者冲突时,最终尺寸会被约束在 min/max 区间内。官方文档给出的合成公式是:
width = MAX(minWidth, MIN(maxWidth, width))
height = MAX(minHeight, MIN(maxHeight, height))
4.6 状态驱动的动态尺寸
typescript
@State avatarSize: number = 64;
Column()
.width(this.avatarSize) // 宽高跟随状态变量
.height(this.avatarSize)
.borderRadius(this.avatarSize / 2)
Slider({ value: this.avatarSize, min: 40, max: 120, step: 1 })
.onChange((value: number, mode: SliderChangeMode) => {
this.avatarSize = value; // 滑动即改状态,UI 自动刷新
})
尺寸属性接收的是表达式,不限于常量。@State 变量变化后,引用它的属性会自动重新渲染,这是声明式 UI"数据驱动界面"的直观体现------圆角半径 this.avatarSize / 2 还顺便保证了滑块拉到任何值都是正圆。
五、尺寸设置决策流程图
实际开发中按下面这条路径选属性,基本不会走弯路:
#mermaid-svg-7VL3BmYtpThzbx21{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-7VL3BmYtpThzbx21 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-7VL3BmYtpThzbx21 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-7VL3BmYtpThzbx21 .error-icon{fill:#552222;}#mermaid-svg-7VL3BmYtpThzbx21 .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-7VL3BmYtpThzbx21 .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-7VL3BmYtpThzbx21 .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-7VL3BmYtpThzbx21 .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-7VL3BmYtpThzbx21 .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-7VL3BmYtpThzbx21 .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-7VL3BmYtpThzbx21 .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-7VL3BmYtpThzbx21 .marker{fill:#333333;stroke:#333333;}#mermaid-svg-7VL3BmYtpThzbx21 .marker.cross{stroke:#333333;}#mermaid-svg-7VL3BmYtpThzbx21 svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-7VL3BmYtpThzbx21 p{margin:0;}#mermaid-svg-7VL3BmYtpThzbx21 .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-7VL3BmYtpThzbx21 .cluster-label text{fill:#333;}#mermaid-svg-7VL3BmYtpThzbx21 .cluster-label span{color:#333;}#mermaid-svg-7VL3BmYtpThzbx21 .cluster-label span p{background-color:transparent;}#mermaid-svg-7VL3BmYtpThzbx21 .label text,#mermaid-svg-7VL3BmYtpThzbx21 span{fill:#333;color:#333;}#mermaid-svg-7VL3BmYtpThzbx21 .node rect,#mermaid-svg-7VL3BmYtpThzbx21 .node circle,#mermaid-svg-7VL3BmYtpThzbx21 .node ellipse,#mermaid-svg-7VL3BmYtpThzbx21 .node polygon,#mermaid-svg-7VL3BmYtpThzbx21 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-7VL3BmYtpThzbx21 .rough-node .label text,#mermaid-svg-7VL3BmYtpThzbx21 .node .label text,#mermaid-svg-7VL3BmYtpThzbx21 .image-shape .label,#mermaid-svg-7VL3BmYtpThzbx21 .icon-shape .label{text-anchor:middle;}#mermaid-svg-7VL3BmYtpThzbx21 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-7VL3BmYtpThzbx21 .rough-node .label,#mermaid-svg-7VL3BmYtpThzbx21 .node .label,#mermaid-svg-7VL3BmYtpThzbx21 .image-shape .label,#mermaid-svg-7VL3BmYtpThzbx21 .icon-shape .label{text-align:center;}#mermaid-svg-7VL3BmYtpThzbx21 .node.clickable{cursor:pointer;}#mermaid-svg-7VL3BmYtpThzbx21 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-7VL3BmYtpThzbx21 .arrowheadPath{fill:#333333;}#mermaid-svg-7VL3BmYtpThzbx21 .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-7VL3BmYtpThzbx21 .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-7VL3BmYtpThzbx21 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-7VL3BmYtpThzbx21 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-7VL3BmYtpThzbx21 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-7VL3BmYtpThzbx21 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-7VL3BmYtpThzbx21 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-7VL3BmYtpThzbx21 .cluster text{fill:#333;}#mermaid-svg-7VL3BmYtpThzbx21 .cluster span{color:#333;}#mermaid-svg-7VL3BmYtpThzbx21 div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-7VL3BmYtpThzbx21 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-7VL3BmYtpThzbx21 rect.text{fill:none;stroke-width:0;}#mermaid-svg-7VL3BmYtpThzbx21 .icon-shape,#mermaid-svg-7VL3BmYtpThzbx21 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-7VL3BmYtpThzbx21 .icon-shape p,#mermaid-svg-7VL3BmYtpThzbx21 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-7VL3BmYtpThzbx21 .icon-shape .label rect,#mermaid-svg-7VL3BmYtpThzbx21 .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-7VL3BmYtpThzbx21 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-7VL3BmYtpThzbx21 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-7VL3BmYtpThzbx21 :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 是
否
跟随父容器比例
混合单位计算
兄弟间按比例分
是
否
需要设置组件尺寸
尺寸是否固定不变?
width / height 传固定值,单位 vp
希望如何自适应?
width('50%') 百分比
width('calc(100% - 32vp)')
layoutWeight 设置权重
需要限制范围吗?
constraintSize 设置 min / max
完成
六、避坑指南
- 子组件溢出不报错 :子组件宽高大于父组件时会直接溢出显示在父组件外部,编译期没有任何提示。要么改小尺寸,要么给父容器加
.clip(true)裁剪。 - 百分比找不到参照 :百分比参考"最近设置了固定大小的祖先"。如果整条链上的容器都是
wrap_content,百分比会退化。排查时自下而上找一个确定尺寸的节点。 layoutWeight与flexGrow不要混用 :同一容器内只要有一个子组件的layoutWeight大于 0,所有子组件就不再基于 flexShrink/flexGrow 布局。一个容器选定一种分配方式即可。constraintSize会覆盖width:排查"width 明明写了却不生效"的问题时,先检查有没有constraintSize把它夹住了。'auto'的语义因组件而异 :Row/Column/RelativeContainer 的width('auto')是自适应子组件;TextInput 的width('auto')是自适应已输入文本。同名不同义,跨组件迁移代码时容易想当然。
总结
尺寸设置的规则可以收进三句话:
- 取值四件套:数字(vp)、百分比(参考最近固定祖先)、calc(API 10+,运算符留空格)、资源引用;
- 权重优先 :等分与比例分配用
layoutWeight,它分配时忽略子组件自身宽高; - 约束兜底 :内容不定长时用
constraintSize的 min/max 兜住边界,其优先级高于width/height。
下一篇我们进入位置设置:用 position、offset、markAnchor 把悬浮按钮、角标和气泡精确钉在页面的任何角落。
参考资料
- 官方文档《尺寸设置》:https://developer.huawei.com/consumer/cn/doc/doccenter-references/api/ts-universal-attributes-size
- 官方文档《Flex 布局》(layoutWeight 与 flexGrow 的关系)